#!/usr/bin/env bash
# Interactive importer for the Stremio Appliance image.
# Asks which hypervisor, storage, and network, then imports the OVA/OVF *correctly* — a virtio
# disk controller + a NIC — so it boots on the first try (avoids the LSI-controller hang and the
# missing-network-card gotcha you get from a bare `qm importovf`).
#
# Usage:  ./import-appliance.sh [path-to.ova|.ovf]
# Run it on the Proxmox node (needs `qm`) or on a host with VirtualBox (`VBoxManage`).
set -uo pipefail

say() { printf '%s\n' "$*"; }
ask() { # ask "Prompt" "default" -> prints the answer
  local p="$1" d="${2:-}" a
  if [ -n "$d" ]; then read -rp "$p [$d]: " a; printf '%s\n' "${a:-$d}"
  else read -rp "$p: " a; printf '%s\n' "$a"; fi
}

# --- locate the image ---
IMG="${1:-}"
[ -n "$IMG" ] || IMG="$(ask "Path to the .ova or .ovf")"
[ -f "$IMG" ] || { say "Not found: $IMG"; exit 1; }

# --- pick hypervisor (auto-detected default) ---
detected=""
command -v qm          >/dev/null 2>&1 && detected="proxmox"
[ -z "$detected" ] && command -v VBoxManage >/dev/null 2>&1 && detected="virtualbox"
say ""
say "Which hypervisor?   1) Proxmox   2) VirtualBox   3) other"
def=1; [ "$detected" = virtualbox ] && def=2
case "$(ask "Choose" "$def")" in
  1) HV=proxmox ;;
  2) HV=virtualbox ;;
  *) say "For other hypervisors: import the .ova in the app's Import wizard, and choose a VirtIO/SCSI disk + a network adapter."; exit 0 ;;
esac

# ----------------------------------------------------------------------------- Proxmox
if [ "$HV" = proxmox ]; then
  command -v qm >/dev/null 2>&1 || { say "ERROR: 'qm' not found — run this on the Proxmox node."; exit 1; }

  OVF="$IMG"; WORK=""
  if [[ "$IMG" == *.ova ]]; then
    WORK="$(dirname "$IMG")/.ova-extract.$$"      # extract beside the OVA (avoids small /tmp tmpfs)
    mkdir -p "$WORK"; say "Unpacking OVA ..."; tar -xf "$IMG" -C "$WORK"
    OVF="$(ls "$WORK"/*.ovf 2>/dev/null | head -1)"
    [ -f "$OVF" ] || { say "ERROR: no .ovf inside the OVA"; rm -rf "$WORK"; exit 1; }
  fi

  say ""; say "Storage pools:"; pvesm status 2>/dev/null | awk 'NR>1{printf "  - %s (%s)\n",$1,$2}'
  STORAGE="$(ask "Disk storage" "local-lvm")"
  say "Network bridges:"; ls /sys/class/net 2>/dev/null | grep -E '^vmbr' | sed 's/^/  - /'
  BRIDGE="$(ask "Network bridge" "vmbr0")"
  VMID="$(ask "VM ID" "$(qm nextid 2>/dev/null || echo 9999)")"
  NAME="$(ask "VM name" "stremio-appliance")"
  MEM="$(ask "Memory (MB)" "2048")"
  CORES="$(ask "CPU cores" "2")"
  DISK="$(ask "VM disk size (GB)" "64")"

  say ""; say "Importing -> VM $VMID  (storage $STORAGE, NIC on $BRIDGE) ..."
  qm importovf "$VMID" "$OVF" "$STORAGE" || { say "ERROR: qm importovf failed"; [ -n "$WORK" ] && rm -rf "$WORK"; exit 1; }
  # virtio-scsi controller (the image has the driver; default LSI does not) + a NIC
  qm set "$VMID" --name "$NAME" --memory "$MEM" --cores "$CORES" \
        --scsihw virtio-scsi-pci --net0 "virtio,bridge=$BRIDGE" --agent enabled=1 >/dev/null
  # Grow the imported boot disk to the requested size (firstboot.sh runs growpart+resize2fs).
  if printf '%s' "$DISK" | grep -qE '^[0-9]+$'; then
    DKEY="$(qm config "$VMID" | awk -F: '/^(scsi|sata|virtio|ide)[0-9]+:/ && /import|vm-/{print $1; exit}')"
    [ -z "$DKEY" ] && DKEY="$(qm config "$VMID" | awk -F: '/^(scsi|sata|virtio)[0-9]+:/{print $1; exit}')"
    if [ -n "$DKEY" ]; then
      say "Resizing $DKEY to ${DISK}G (grow-only) ..."
      qm disk resize "$VMID" "$DKEY" "${DISK}G" 2>/dev/null \
        || say "Note: resize skipped (disk already >= ${DISK}G, or resize failed)."
    else
      say "Note: could not identify the boot disk to resize; leaving the default size."
    fi
  fi
  [ -n "$WORK" ] && rm -rf "$WORK"
  say "Created VM $VMID."

  if [ "$(ask "Start it now? (y/n)" "y")" = y ]; then
    qm start "$VMID" && say "Started. Open VM $VMID's console, note the IP it shows, then browse http://<ip>:8090"
  fi
  exit 0
fi

# ----------------------------------------------------------------------------- VirtualBox
if [ "$HV" = virtualbox ]; then
  command -v VBoxManage >/dev/null 2>&1 || { say "ERROR: 'VBoxManage' not found."; exit 1; }
  [[ "$IMG" == *.ova ]] || { say "ERROR: VirtualBox imports the .ova file (not .ovf)."; exit 1; }
  NAME="$(ask "VM name" "stremio-appliance")"
  say "Network:  1) NAT (simple, only this host reaches it)   2) Bridged (appears on your LAN — recommended)"
  net="$(ask "Choose" "2")"
  say "Importing ..."; VBoxManage import "$IMG" --vsys 0 --vmname "$NAME" || { say "ERROR: import failed"; exit 1; }
  say "Disk size: VirtualBox can't resize the imported VMDK in place. To enlarge it, clone to VDI"
  say "  (VBoxManage clonemedium disk <in.vmdk> <out.vdi> --format VDI), then"
  say "  VBoxManage modifymedium disk <out.vdi> --resize <MB>, and attach it. The image grows the"
  say "  filesystem automatically on next boot."
  if [ "$net" = 2 ]; then
    IFACE="$(VBoxManage list bridgedifs | awk -F': +' '/^Name:/{print $2; exit}')"
    [ -n "$IFACE" ] && VBoxManage modifyvm "$NAME" --nic1 bridged --bridgeadapter1 "$IFACE"
  fi
  if [ "$(ask "Start it now? (y/n)" "y")" = y ]; then
    VBoxManage startvm "$NAME" --type headless && say "Started. Find its IP on your router, then browse http://<ip>:8090"
  fi
  exit 0
fi
