#!/bin/bash
# CDM Linux Installer
# Run from Arch live USB: curl -s https://repo.cdm.space/provision/install.sh | bash
set -e

REPO="https://repo.cdm.space/provision"

echo ""
echo "  ██████╗██████╗ ███╗   ███╗"
echo " ██╔════╝██╔══██╗████╗ ████║"
echo " ██║     ██║  ██║██╔████╔██║"
echo " ██║     ██║  ██║██║╚██╔╝██║"
echo " ╚██████╗██████╔╝██║ ╚═╝ ██║"
echo "  ╚═════╝╚═════╝ ╚═╝     ╚═╝"
echo ""
echo "  CDM Linux Installer"
echo ""

# Check we're running from the live ISO
if [ ! -f /run/archiso/bootmnt/arch/pkglist.x86_64.txt ] 2>/dev/null; then
    echo "WARNING: This doesn't look like an Arch live USB."
    echo "Proceed anyway? (y/N)"
    read -r -n 1 REPLY
    echo
    [[ ! $REPLY =~ ^[Yy]$ ]] && exit 1
fi

# Check network
if ! ping -c1 -W3 archlinux.org &>/dev/null; then
    echo "ERROR: No network connection."
    echo "Connect WiFi first: iwctl station wlan0 connect CDM-5Ghz"
    exit 1
fi
echo "[OK] Network connected"

# Detect target disk (NVMe preferred, skip removable/small drives)
TARGET_DISK=""
for disk in /dev/nvme0n1 /dev/nvme1n1 /dev/sda /dev/sdb; do
    [ -b "$disk" ] || continue

    # Skip removable drives (USB sticks)
    BASENAME=$(basename "$disk")
    # NVMe: check parent device
    if [[ "$BASENAME" == nvme* ]]; then
        REMOVABLE=0
    else
        REMOVABLE=$(cat "/sys/block/$BASENAME/removable" 2>/dev/null || echo 1)
    fi
    [ "$REMOVABLE" = "1" ] && continue

    # Skip small drives (<100GB)
    SIZE_BYTES=$(lsblk -b -dn -o SIZE "$disk" 2>/dev/null || echo 0)
    [ "$SIZE_BYTES" -lt 100000000000 ] && continue

    TARGET_DISK="$disk"
    break
done

if [ -z "$TARGET_DISK" ]; then
    echo "ERROR: No suitable disk found (need >100GB, non-removable)."
    echo "Available disks:"
    lsblk -d -o NAME,SIZE,TYPE,RM,TRAN
    exit 1
fi

SIZE_HUMAN=$(lsblk -dn -o SIZE "$TARGET_DISK")
echo "[OK] Target disk: $TARGET_DISK ($SIZE_HUMAN)"
echo ""
echo "  WARNING: ALL DATA ON $TARGET_DISK WILL BE ERASED!"
echo ""
read -r -p "  Type YES to continue: " CONFIRM
[ "$CONFIRM" != "YES" ] && { echo "Aborted."; exit 1; }

# Download configs
echo ""
echo "[..] Downloading configuration..."
curl -sf "$REPO/config.json" -o /tmp/cdm-config.json || { echo "ERROR: Failed to download config.json"; exit 1; }
curl -sf "$REPO/creds.json" -o /tmp/cdm-creds.json || { echo "ERROR: Failed to download creds.json"; exit 1; }
echo "[OK] Configuration downloaded"

# Inject detected disk and calculate root partition size
ROOT_SIZE_GIB=$(( $(lsblk -b -dn -o SIZE "$TARGET_DISK") / 1073741824 - 2 ))
sed -i "s|REPLACE_DISK|$TARGET_DISK|g; s|99999|$ROOT_SIZE_GIB|g" /tmp/cdm-config.json
echo "[OK] Disk: $TARGET_DISK, root partition: ${ROOT_SIZE_GIB} GiB"

# Run archinstall
echo ""
echo "[..] Starting installation (this takes 10-15 minutes)..."
echo ""
archinstall --config /tmp/cdm-config.json --creds /tmp/cdm-creds.json --silent

echo ""
echo "  ╔══════════════════════════════════════╗"
echo "  ║   CDM Linux installed successfully   ║"
echo "  ║   Remove USB and reboot              ║"
echo "  ╚══════════════════════════════════════╝"
echo ""
