#!/bin/bash
# fix-evo-key.sh — boot from the Ubuntu installer USB → Ctrl+Alt+F2 → curl this script
# Mounts the EVO-T1's NVMe Ubuntu install, adds Claude Server's pubkey, fixes perms, reboots.
set -e

MOUNT=/mnt/evo-fix
PUBKEY_URL=https://downloads.domian.network/claude/claude-server.pub
LV=/dev/mapper/ubuntu--vg-ubuntu--lv

echo "[1/7] Activating LVM volume groups..."
vgchange -ay 2>/dev/null || true

echo "[2/7] Mounting installed Ubuntu root LV ($LV)..."
mkdir -p "$MOUNT"
mount "$LV" "$MOUNT" || { echo "FATAL: could not mount $LV — try 'lvscan' to find the right LV"; exit 1; }

echo "[3/7] Verifying it's an Ubuntu install with /home/claude/..."
[[ -d "$MOUNT/home/claude" ]] || { echo "FATAL: /home/claude not found on this LV — wrong volume?"; ls "$MOUNT/home/" 2>&1; umount "$MOUNT"; exit 1; }
echo "    ✓ Found /home/claude"

echo "[4/7] Ensuring /home/claude/.ssh/ exists..."
mkdir -p "$MOUNT/home/claude/.ssh"

echo "[5/7] Curling Claude Server pubkey from $PUBKEY_URL..."
curl -fsSL "$PUBKEY_URL" >> "$MOUNT/home/claude/.ssh/authorized_keys" || { echo "FATAL: curl failed — check network on the live ISO"; umount "$MOUNT"; exit 1; }
echo "    ✓ Appended pubkey"

echo "[6/7] Fixing perms + ownership..."
chown -R 1000:1000 "$MOUNT/home/claude/.ssh"
chmod 700 "$MOUNT/home/claude/.ssh"
chmod 600 "$MOUNT/home/claude/.ssh/authorized_keys"

echo "[7/7] Unmounting + rebooting..."
umount "$MOUNT"
echo
echo "✅ DONE. Pulling USB and rebooting in 5 sec..."
sleep 5
reboot
