#!/bin/sh
# clawdie-vps-migrate.sh
# Migrate a Linux VPS to FreeBSD + Clawdie-AI
#
# Usage:
#   curl -fsSL https://clawdie.si/vps.sh | sh
#   # or
#   ./clawdie-vps-migrate.sh https://your-ssh-key-url
#
# Requirements:
#   - Linux VPS with rescue mode or root access
#   - At least 2GB RAM (mfsBSD runs in RAM)
#   - Disk will be COMPLETELY ERASED
#
# This script:
#   1. Downloads mfsBSD with Clawdie payload
#   2. Writes to disk (overwrites everything!)
#   3. Configures GRUB to boot mfsBSD
#   4. Reboots
#
# After reboot:
#   ssh -p 1022 mfsbsd@your-ip
#   # password: clawdie2026
#   /usr/local/share/clawdie-iso/firstboot.sh

set -e

SSH_KEY_URL="${1:-}"
CLAWDIE_MFSBSD_URL="https://clawdie.si/clawdie-mfsbsd-latest.img.gz"
CLAWDIE_MFSBSD_SHA256_URL="https://clawdie.si/clawdie-mfsbsd-latest.img.gz.sha256"
MFSBSD_PASSWORD="clawdie2026"

echo "============================================"
echo " Clawdie-VPS Migration"
echo " WARNING: This will ERASE ALL DATA on disk"
echo "============================================"
echo ""

# Detect disk
DISK=$(lsblk -nd -o NAME,ROTA | grep '1$' | head -1 | awk '{print $1}')
if [ -z "$DISK" ]; then
    DISK=$(ls /dev/vd? /dev/sd? 2>/dev/null | head -1 | sed 's|/dev/||')
fi
if [ -z "$DISK" ]; then
    echo "ERROR: Cannot detect disk. Set DISK= manually."
    exit 1
fi
echo "Target disk: /dev/${DISK}"
echo ""

# Confirm
read -p "Continue? ALL DATA ON /dev/${DISK} WILL BE LOST! (type 'yes'): " CONFIRM
if [ "$CONFIRM" != "yes" ]; then
    echo "Aborted."
    exit 1
fi

# Download mfsBSD with Clawdie payload
echo "==> Downloading Clawdie-mfsBSD..."
TMPDIR=$(mktemp -d)
curl -L --progress-bar -o "${TMPDIR}/clawdie-mfsbsd.img.gz" "$CLAWDIE_MFSBSD_URL"

# Verify checksum
curl -L -o "${TMPDIR}/clawdie-mfsbsd.img.gz.sha256" "$CLAWDIE_MFSBSD_SHA256_URL"
cd "$TMPDIR"
sha256sum -c clawdie-mfsbsd.img.gz.sha256 || { echo "ERROR: Checksum mismatch!"; exit 1; }
cd - > /dev/null

# Decompress
echo "==> Decompressing..."
gunzip "${TMPDIR}/clawdie-mfsbsd.img.gz"
IMG_SIZE=$(stat -c%s "${TMPDIR}/clawdie-mfsbsd.img")
echo "    Image size: $((IMG_SIZE / 1024 / 1024)) MB"

# Write to disk
echo "==> Writing to /dev/${DISK} (this takes a few minutes)..."
dd if="${TMPDIR}/clawdie-mfsbsd.img" of="/dev/${DISK}" bs=4M status=progress conv=fsync

# Sync
sync

# Cleanup
rm -rf "$TMPDIR"

echo ""
echo "============================================"
echo " Migration complete!"
echo ""
echo " After reboot:"
echo "   ssh -p 1022 mfsbsd@$(curl -s ifconfig.me)"
echo "   Password: ${MFSBSD_PASSWORD}"
echo ""
echo " Then run:"
echo "   /usr/local/share/clawdie-iso/firstboot-vps.sh"
echo "============================================"
echo ""
read -p "Press Enter to reboot now (or Ctrl+C to abort)..."
reboot
