#!/bin/bash
set -e

# Configuration
read -p "Enter Host Domain (e.g. tilde.red): " HOST
REMOTE_DIR="/downloads"

echo "--- Lean-VM Client Bootstrap ---"
read -p "Enter Username: " USERNAME
echo ""

# Find the user's SSH private key automatically
SSH_KEY=""
for candidate in ~/.ssh/id_ed25519 ~/.ssh/id_rsa ~/.ssh/id_ecdsa ~/.ssh/id_dsa; do
    if [ -f "$candidate" ] && [ ! -d "$candidate" ]; then
        SSH_KEY="$candidate"
        break
    fi
done

if [ -z "$SSH_KEY" ]; then
    echo "Error: No SSH private key found."
    echo ""
    echo "Lean-VM uses key-based authentication only (passwords are disabled)."
    echo "Please place your SSH public key on the server, then re-run this script."
    echo ""
    echo "If you don't have an SSH key yet, generate one:"
    echo "  ssh-keygen -t ed25519 -C \"your_email@example.com\""
    echo ""
    echo "Then send the public key (~/.ssh/id_ed25519.pub) to a sysadmin."
    exit 1
fi

echo "[*] Using SSH key: $SSH_KEY"

if [ ! -r "$SSH_KEY" ]; then
    echo "Error: SSH key is not readable. Check permissions on $SSH_KEY"
    exit 1
fi

mkdir -p lean-vm-guest
cd lean-vm-guest

echo "[*] Downloading system artifacts and user disk..."

# The chroot SFTP root maps to the user's home, so /downloads = ~/downloads
scp -i "$SSH_KEY" -r "$USERNAME@$HOST:$REMOTE_DIR/." .

if [ -d "$REMOTE_DIR" ]; then
    mv "$REMOTE_DIR"/* .
    rm -rf "$REMOTE_DIR"
fi

echo "[*] Creating launcher script..."
cat <<EOF > start_vm.sh
#!/bin/bash
QEMU_BIN="qemu-system-i386"

if ! command -v \$QEMU_BIN &> /dev/null; then
    echo "Error: \$QEMU_BIN not found. Please install QEMU."
    exit 1
fi

echo "[*] Launching Lean-VM for $USERNAME..."
\$QEMU_BIN \
  -kernel bzImage \
  -initrd initrd \
  -drive file=$USERNAME.qcow2,if=virtio \
  -net nic,model=virtio -net user \
  -serial mon:stdio \
  -append "console=ttyS0 root=/dev/ram0"
EOF

chmod +x start_vm.sh

echo "--------------------------------------------------"
echo "[+] Setup Complete!"
echo "To start your VM, run: ./start_vm.sh"
echo "--------------------------------------------------"
