#!/usr/bin/env bash
set -euo pipefail

PIMOX_HOST="${LAB_PIMOX_HOST:-${LAB_CLUSTER_PIMOX_HOST:-192.168.100.80}}"
PIMOX_USER="${LAB_PIMOX_USER:-${LAB_CLUSTER_PIMOX_USER:-jv}}"
PIMOX_KEY="${LAB_PIMOX_SSH_KEY_PATH:-${LAB_CLUSTER_PIMOX_SSH_KEY_PATH:-${HOME}/.ssh/id_ed25519}}"

usage() {
    echo "Usage: ./jeannie pimox {status [VMID]|console VMID}" >&2
    exit 2
}

valid_vmid() {
    [[ "${1:-}" =~ ^[0-9]+$ ]] && ((10#$1 > 0))
}

pimox_ssh() {
    ssh -i "${PIMOX_KEY}" -o BatchMode=yes -o ConnectTimeout=10 \
        -o StrictHostKeyChecking=accept-new "${PIMOX_USER}@${PIMOX_HOST}" "$@"
}

status_vm() {
    local vmid="$1"
    if ! valid_vmid "${vmid}"; then
        echo "VMID must be numeric: ${vmid}" >&2
        return 2
    fi
    pimox_ssh "sudo qm status ${vmid}; echo '--- config ---'; sudo qm config ${vmid} | grep -E '^(name|cores|sockets|memory|cpu|agent|serial[0-9]*):' || true; echo '--- guest agent ---'; sudo qm agent ${vmid} ping 2>&1 || true"
}

case "${1:-}" in
    status)
        if [[ -n "${2:-}" ]]; then
            status_vm "$2"
        else
            echo "Pimox host: ${PIMOX_USER}@${PIMOX_HOST}"
            pimox_ssh "sudo qm list"
        fi
        ;;
    console)
        if [[ "${JEANNIE_REMOTE_SERVER:-false}" == true ]]; then
            echo "Interactive Pimox console cannot run through the remote API; SSH to Debian and run ./jeannie pimox console VMID." >&2
            exit 2
        fi
        valid_vmid "${2:-}" || usage
        exec ssh -tt -i "${PIMOX_KEY}" -o ConnectTimeout=10 \
            -o StrictHostKeyChecking=accept-new "${PIMOX_USER}@${PIMOX_HOST}" \
            "sudo qm terminal $2"
        ;;
    *)
        usage
        ;;
esac
