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

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
source "${REPO_ROOT}/scripts/cluster-env.sh"
HOMELAB_STATE_DIR="${HOMELAB_STATE_DIR:-${XDG_DATA_HOME:-${HOME}/.local/share}/homelab}"
BACKUP_DIR="${HOMELAB_PROFILE_BACKUP_DIR:-${HOMELAB_STATE_DIR}/profile-backups}"
HOMELAB_BACKUP_STAGE=""
HOMELAB_BACKUP_PLAIN_ARCHIVE=""
KUBECONFIG_PATH="${KUBECONFIG_PATH:-${KUBECONFIG:-${HOME}/.kube/config}}"
PIMOX_HOST="${LAB_PIMOX_HOST:-${TF_VAR_pimox_host:-192.168.100.80}}"
PIMOX_USER="${LAB_PIMOX_USER:-${TF_VAR_pimox_user:-jv}}"
PIMOX_KEY="${LAB_PIMOX_SSH_KEY_PATH:-${TF_VAR_pimox_ssh_key_path:-${HOME}/.ssh/id_ed25519}}"
PIMOX_QM_BIN="${LAB_PIMOX_QM_BIN:-${TF_VAR_pimox_qm_bin:-/usr/sbin/qm}}"
PIMOX_CONTROL_PLANE_VMID="${LAB_CLUSTER_PIMOX_CONTROL_PLANE_VMID:-${TF_VAR_pimox_control_plane_vmid:-9001}}"
PIMOX_WORKER_BASE_VMID="${LAB_PIMOX_WORKER_BASE_VMID:-${TF_VAR_pimox_worker_base_vmid:-9010}}"
PIMOX_WORKER_COUNT="${LAB_CLUSTER_PIMOX_WORKER_COUNT:-${LAB_PIMOX_WORKER_COUNT:-2}}"
SOPS_CONFIG="${SOPS_CONFIG:-${REPO_ROOT}/.sops.yaml}"
AGE_KEY_FILE="${SOPS_AGE_KEY_FILE:-${HOME}/.config/sops/age/keys.txt}"
OFFSITE_URI="${HOMELAB_BACKUP_OFFSITE_URI:-}"
GITEA_BACKUP_DIR="${LAB_GITEA_BACKUP_DIR:-/home/jv/backups/gitea}"
TOFU_BACKUP_DIR="${HOMELAB_TOFU_STATE_BACKUP_DIR:-${HOMELAB_STATE_DIR}/tofu-state-backups}"

usage() {
    cat <<'EOF'
Usage: scripts/homelab-backup {pimox-profile|validate-latest}

Creates a Pimox-aware, age-encrypted disaster-recovery profile archive.

Optional env:
  HOMELAB_PROFILE_BACKUP_DIR      Local encrypted archive directory.
  HOMELAB_BACKUP_OFFSITE_URI      file:///path, /path, or ssh://user@host/path.
  HOMELAB_BACKUP_OFFSITE_REQUIRED Set true to fail when the optional offsite push fails.
  KUBECONFIG_PATH                 Kubeconfig for app inventory.
EOF
}

log() {
    printf '%s\n' "$*"
}

require_command() {
    command -v "$1" >/dev/null 2>&1 || {
        echo "$1 is required." >&2
        exit 1
    }
}

latest_file() {
    local directory="$1"
    local pattern="$2"
    find "${directory}" -maxdepth 1 -type f -name "${pattern}" -printf '%T@ %p\n' 2>/dev/null |
        sort -n |
        tail -1 |
        sed 's/^[^ ]* //'
}

age_recipient() {
    local recipient="${HOMELAB_BACKUP_AGE_RECIPIENT:-}"
    if [[ -n "${recipient}" ]]; then
        printf '%s\n' "${recipient}"
        return 0
    fi
    if [[ -s "${SOPS_CONFIG}" ]]; then
        awk '/^[[:space:]]*age:[[:space:]]*age1/ { print $2; exit }' "${SOPS_CONFIG}"
    fi
}

safe_run() {
    local output="$1"
    shift
    if "$@" >"${output}" 2>&1; then
        return 0
    fi
    {
        printf 'command failed:'
        printf ' %q' "$@"
        printf '\n'
    } >>"${output}"
    return 0
}

copy_if_present() {
    local source="$1"
    local destination="$2"
    if [[ -e "${source}" ]]; then
        mkdir -p "$(dirname "${destination}")"
        cp -a "${source}" "${destination}"
    fi
}

collect_repo_inventory() {
    local stage="$1"
    local repo_dir="${stage}/repo"
    mkdir -p "${repo_dir}"

    git -C "${REPO_ROOT}" rev-parse HEAD >"${repo_dir}/HEAD.txt"
    git -C "${REPO_ROOT}" status --short >"${repo_dir}/status-short.txt"
    git -C "${REPO_ROOT}" remote -v >"${repo_dir}/remotes.txt"
    git -C "${REPO_ROOT}" ls-files >"${repo_dir}/tracked-files.txt"
    git -C "${REPO_ROOT}" ls-files '*.secret.yaml' '*.secret.yml' '*.secret.json' '*.enc.yaml' '*.enc.yml' '*.enc.json' >"${repo_dir}/sops-secret-files.txt"
    git -C "${REPO_ROOT}" ls-files 'apps/**' 'bootstrap/**' 'infra/**' '.sops.yaml' 'homelab.yml' >"${repo_dir}/gitops-source-files.txt"

    while IFS= read -r file; do
        [[ -n "${file}" ]] || continue
        copy_if_present "${REPO_ROOT}/${file}" "${stage}/gitops-source/${file}"
    done <"${repo_dir}/gitops-source-files.txt"

    if command -v sha256sum >/dev/null 2>&1; then
        while IFS= read -r file; do
            [[ -n "${file}" ]] || continue
            (cd "${REPO_ROOT}" && sha256sum "${file}") >>"${repo_dir}/sops-secret-sha256.txt"
        done <"${repo_dir}/sops-secret-files.txt"
    fi
}

collect_tofu_state() {
    local stage="$1"
    local state_dir="${stage}/tofu-state"
    local path
    mkdir -p "${state_dir}"

    for path in \
        bootstrap/provisioning/terraform.tfstate \
        bootstrap/provisioning/terraform.tfstate.backup \
        bootstrap/cluster/terraform.tfstate \
        bootstrap/cluster/terraform.tfstate.backup \
        bootstrap/platform/terraform.tfstate \
        bootstrap/platform/terraform.tfstate.backup \
        bootstrap/sso-grafana/terraform.tfstate \
        bootstrap/sso-grafana/terraform.tfstate.backup \
        bootstrap/sso-gitea/terraform.tfstate \
        bootstrap/sso-gitea/terraform.tfstate.backup \
        bootstrap/apps/terraform.tfstate \
        bootstrap/apps/terraform.tfstate.backup \
        bootstrap/edge/terraform.tfstate \
        bootstrap/edge/terraform.tfstate.backup \
        .lab/cluster-workers.auto.tfvars.json \
        .lab/pimox-workers.tsv \
        .lab/manual-workers.tsv; do
        copy_if_present "${REPO_ROOT}/${path}" "${state_dir}/${path}"
    done

    latest_file "${TOFU_BACKUP_DIR}" 'tofu-state-*.tgz' >"${state_dir}/latest-tofu-backup.txt" || true
    if [[ -d "${HOMELAB_STATE_DIR}/clusters" ]]; then
        while IFS= read -r path; do
            copy_if_present "${path}" "${state_dir}/clusters/${path#"${HOMELAB_STATE_DIR}/clusters/"}"
        done < <(find "${HOMELAB_STATE_DIR}/clusters" -type d -name .terraform -prune -o \
            -type f \( -name identity.json -o -name terraform.tfstate -o -name terraform.tfstate.backup \
            -o -path '*/legacy-adoptions/*.json' \) -print)
    fi
}

collect_gitea_backup_inventory() {
    local stage="$1"
    local gitea_dir="${stage}/gitea"
    local latest
    mkdir -p "${gitea_dir}"

    latest="$(latest_file "${GITEA_BACKUP_DIR}" 'gitea-*.zip' || true)"
    if [[ -n "${latest}" ]]; then
        printf '%s\n' "${latest}" >"${gitea_dir}/latest-gitea-backup.txt"
        cp -a "${latest}" "${gitea_dir}/latest-gitea-backup.zip"
        if command -v sha256sum >/dev/null 2>&1; then
            sha256sum "${latest}" >"${gitea_dir}/latest-gitea-backup.sha256"
        fi
    else
        printf 'missing\n' >"${gitea_dir}/latest-gitea-backup.txt"
    fi
}

collect_kube_inventory() {
    local stage="$1"
    local kube_dir="${stage}/kubernetes"
    mkdir -p "${kube_dir}"

    if ! command -v kubectl >/dev/null 2>&1 || [[ ! -s "${KUBECONFIG_PATH}" ]]; then
        printf 'kubectl or kubeconfig unavailable\n' >"${kube_dir}/SKIPPED.txt"
        return 0
    fi

    safe_run "${kube_dir}/nodes.yaml" kubectl --kubeconfig "${KUBECONFIG_PATH}" get nodes -o yaml
    safe_run "${kube_dir}/namespaces.yaml" kubectl --kubeconfig "${KUBECONFIG_PATH}" get namespaces -o yaml
    safe_run "${kube_dir}/argocd-applications.yaml" kubectl --kubeconfig "${KUBECONFIG_PATH}" get applications.argoproj.io -A -o yaml
    safe_run "${kube_dir}/workloads.yaml" kubectl --kubeconfig "${KUBECONFIG_PATH}" get deploy,statefulset,daemonset,job,cronjob -A -o yaml
    safe_run "${kube_dir}/networking.yaml" kubectl --kubeconfig "${KUBECONFIG_PATH}" get svc,ingress,endpoints,endpointslice -A -o yaml
    safe_run "${kube_dir}/storage.yaml" kubectl --kubeconfig "${KUBECONFIG_PATH}" get pv,pvc,storageclass -A -o yaml
}

collect_pimox_inventory() {
    local stage="$1"
    local pimox_dir="${stage}/pimox"
    local vmid
    mkdir -p "${pimox_dir}/vm-configs"

    if ! command -v ssh >/dev/null 2>&1; then
        printf 'ssh unavailable\n' >"${pimox_dir}/SKIPPED.txt"
        return 0
    fi

    safe_run "${pimox_dir}/qm-list.txt" ssh -i "${PIMOX_KEY}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${PIMOX_USER}@${PIMOX_HOST}" "sudo '${PIMOX_QM_BIN}' list"
    safe_run "${pimox_dir}/storage-status.txt" ssh -i "${PIMOX_KEY}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${PIMOX_USER}@${PIMOX_HOST}" "sudo pvesm status"
    safe_run "${pimox_dir}/network-interfaces.txt" ssh -i "${PIMOX_KEY}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${PIMOX_USER}@${PIMOX_HOST}" "ip -brief addr; ip route"

    {
        printf '%s\n' "${PIMOX_CONTROL_PLANE_VMID}"
        seq 0 "$((PIMOX_WORKER_COUNT - 1))" | awk -v base="${PIMOX_WORKER_BASE_VMID}" '{ print base + $1 }'
    } >"${pimox_dir}/managed-vmids.txt"

    while IFS= read -r vmid; do
        [[ -n "${vmid}" ]] || continue
        safe_run "${pimox_dir}/vm-configs/${vmid}.conf" ssh -i "${PIMOX_KEY}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${PIMOX_USER}@${PIMOX_HOST}" "sudo '${PIMOX_QM_BIN}' config '${vmid}'"
        safe_run "${pimox_dir}/vm-configs/${vmid}.status" ssh -i "${PIMOX_KEY}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${PIMOX_USER}@${PIMOX_HOST}" "sudo '${PIMOX_QM_BIN}' status '${vmid}'"
    done <"${pimox_dir}/managed-vmids.txt"
}

write_manifest() {
    local stage="$1"
    cat >"${stage}/MANIFEST.txt" <<EOF
created_utc=$(date -u +%Y-%m-%dT%H:%M:%SZ)
repo=${REPO_ROOT}
git_head=$(git -C "${REPO_ROOT}" rev-parse HEAD 2>/dev/null || true)
cluster_profile=${LAB_CLUSTER_PROFILE:-debian}
kubeconfig=${KUBECONFIG_PATH}
pimox=${PIMOX_USER}@${PIMOX_HOST}
offsite_uri=${OFFSITE_URI:-unset}
EOF
}

push_offsite() {
    local archive="$1"
    local uri="${OFFSITE_URI}"
    local target
    local host
    local path

    if [[ -z "${uri}" ]]; then
        log "Offsite push skipped: HOMELAB_BACKUP_OFFSITE_URI is not set."
        return 0
    fi

    case "${uri}" in
        file://*)
            target="${uri#file://}"
            mkdir -p "${target}"
            cp -a "${archive}" "${target}/"
            ;;
        /*)
            mkdir -p "${uri}"
            cp -a "${archive}" "${uri}/"
            ;;
        ssh://*)
            target="${uri#ssh://}"
            host="${target%%/*}"
            path="/${target#*/}"
            if ! ssh -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${host}" "mkdir -p '${path}'"; then
                echo "Offsite SSH target is unreachable: ${host}" >&2
                return 1
            fi
            if ! scp -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${archive}" "${host}:${path}/"; then
                echo "Offsite SSH upload failed: ${host}:${path}" >&2
                return 1
            fi
            ;;
        *)
            echo "Unsupported HOMELAB_BACKUP_OFFSITE_URI: ${uri}" >&2
            return 1
            ;;
    esac

    log "Pushed encrypted archive to ${uri}."
}

validate_archive() {
    local archive="$1"
    if [[ ! -s "${archive}" ]]; then
        echo "Archive is missing or empty: ${archive}" >&2
        return 1
    fi

    if [[ -s "${AGE_KEY_FILE}" ]] && command -v age >/dev/null 2>&1; then
        age -d -i "${AGE_KEY_FILE}" "${archive}" | tar -tzf - >/dev/null
        log "Restore drill validation ok: encrypted archive decrypts and tar can be listed."
    else
        head -c 32 "${archive}" | grep -q 'age-encryption.org' &&
            log "Restore drill validation partial: archive is age encrypted; no local age identity available for decrypt test."
    fi
}

pimox_profile_backup() {
    local timestamp
    local stage
    local plain_archive
    local encrypted_archive
    local recipient

    require_command tar
    require_command age
    require_command git

    recipient="$(age_recipient)"
    if [[ -z "${recipient}" ]]; then
        echo "No age recipient found. Set HOMELAB_BACKUP_AGE_RECIPIENT or configure .sops.yaml." >&2
        exit 1
    fi

    timestamp="$(date -u +%Y%m%dT%H%M%SZ)"
    mkdir -p "${BACKUP_DIR}"
    stage="$(mktemp -d "/tmp/homelab-pimox-backup-${timestamp}.XXXXXX")"
    plain_archive="$(mktemp "/tmp/homelab-pimox-profile-${timestamp}.XXXXXX.tgz")"
    encrypted_archive="${BACKUP_DIR}/homelab-pimox-profile-${timestamp}.tgz.age"
    HOMELAB_BACKUP_STAGE="${stage}"
    HOMELAB_BACKUP_PLAIN_ARCHIVE="${plain_archive}"

    cleanup() {
        [[ -z "${HOMELAB_BACKUP_STAGE}" ]] || rm -rf "${HOMELAB_BACKUP_STAGE}"
        [[ -z "${HOMELAB_BACKUP_PLAIN_ARCHIVE}" ]] || rm -f "${HOMELAB_BACKUP_PLAIN_ARCHIVE}"
    }
    trap cleanup EXIT

    write_manifest "${stage}"
    collect_repo_inventory "${stage}"
    collect_tofu_state "${stage}"
    collect_gitea_backup_inventory "${stage}"
    collect_kube_inventory "${stage}"
    collect_pimox_inventory "${stage}"

    tar -C "${stage}" -czf "${plain_archive}" .
    age -r "${recipient}" -o "${encrypted_archive}" "${plain_archive}"
    chmod 0600 "${encrypted_archive}"

    validate_archive "${encrypted_archive}"
    # The local encrypted archive is the source consumed by OCI Object
    # Storage.  A legacy SSH offsite target may be unavailable (for example,
    # an old jump-box), so do not prevent the primary backup/upload workflow
    # from completing unless the operator explicitly requires that target.
    if ! push_offsite "${encrypted_archive}"; then
        if [[ "${HOMELAB_BACKUP_OFFSITE_REQUIRED:-false}" == "true" ]]; then
            echo "Offsite backup is required and the push failed." >&2
            exit 1
        fi
        log "WARNING: optional offsite push failed; retaining the local encrypted archive."
    fi
    log "Created encrypted Pimox profile backup: ${encrypted_archive}"
}

validate_latest() {
    local latest
    latest="$(latest_file "${BACKUP_DIR}" 'homelab-pimox-profile-*.tgz.age' || true)"
    if [[ -z "${latest}" ]]; then
        echo "No Pimox profile backup found in ${BACKUP_DIR}." >&2
        exit 1
    fi
    validate_archive "${latest}"
    printf 'latest=%s\n' "${latest}"
}

case "${1:-pimox-profile}" in
    pimox-profile)
        pimox_profile_backup
        ;;
    validate-latest)
        validate_latest
        ;;
    -h | --help | help)
        usage
        ;;
    *)
        usage >&2
        exit 2
        ;;
esac
