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

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ACTION="${1:-status}"
OCI_PROFILE="${OCI_CLI_PROFILE:-${OCI_CONFIG_PROFILE:-DEFAULT}}"
OCI_CONFIG="${OCI_CONFIG_FILE:-${HOME}/.oci/config}"
OCI_REGION="${LAB_OCI_REGION:-${OCI_REGION:-}}"
BUCKET="${LAB_OCI_BACKUP_BUCKET:-${OCI_OBJECT_STORAGE_BUCKET:-}}"
NAMESPACE="${LAB_OCI_BACKUP_BUCKET_NAMESPACE:-}"
PREFIX="${LAB_OCI_BACKUP_PREFIX:-homelab/}"
BACKUP_DIR="${HOMELAB_PROFILE_BACKUP_DIR:-${XDG_DATA_HOME:-${HOME}/.local/share}/homelab/profile-backups}"
AGE_KEY_FILE="${SOPS_AGE_KEY_FILE:-${HOME}/.config/sops/age/keys.txt}"

usage() {
    echo "Usage: ./jeannie backup oci {status|plan|upload|restore-verify|schedule|lifecycle|freshness}" >&2
}

oci_bin=""
if command -v oci >/dev/null 2>&1; then
    oci_bin="$(command -v oci)"
elif [[ -x "${HOME}/.local/share/homelab/venvs/oci-cli/bin/oci" ]]; then
    oci_bin="${HOME}/.local/share/homelab/venvs/oci-cli/bin/oci"
fi

if [[ "${ACTION}" != status && "${ACTION}" != plan && "${ACTION}" != upload && "${ACTION}" != restore-verify && "${ACTION}" != schedule && "${ACTION}" != lifecycle && "${ACTION}" != freshness ]]; then
    usage
    exit 2
fi
if [[ -z "${oci_bin}" || ! -r "${OCI_CONFIG}" || -z "${OCI_REGION}" || -z "${BUCKET}" ]]; then
    "${REPO_ROOT}/scripts/oci-backup-status" "${ACTION}" || true
    if [[ "${ACTION}" == upload || "${ACTION}" == restore-verify ]]; then
        echo "OCI backup prerequisites are incomplete; complete oci-foundation apply and rerun backup oci status." >&2
    fi
    exit 1
fi

case "${ACTION}" in
    schedule)
        exec "${REPO_ROOT}/scripts/oci-backup-schedule"
        ;;
    lifecycle)
        exec "${REPO_ROOT}/scripts/oci-backup-lifecycle"
        ;;
    freshness)
        exec "${REPO_ROOT}/scripts/oci-backup-freshness"
        ;;
esac

if [[ -z "${NAMESPACE}" ]]; then
    NAMESPACE="$(${oci_bin} os ns get --config-file "${OCI_CONFIG}" --profile "${OCI_PROFILE}" \
        --region "${OCI_REGION}" --query data --raw-output)"
fi

latest_archive() {
    find "${BACKUP_DIR}" -maxdepth 1 -type f -name 'homelab-pimox-profile-*.tgz.age' -printf '%T@ %p\n' 2>/dev/null |
        sort -n | tail -1 | sed 's/^[^ ]* //'
}

upload_archive() {
    local archive="$1" object checksum_file
    object="${PREFIX%/}/$(basename "${archive}")"
    checksum_file="$(mktemp)"
    trap 'rm -f "${checksum_file}"' RETURN
    printf '%s  archive.tgz.age\n' "$(sha256sum "${archive}" | awk '{print $1}')" >"${checksum_file}"
    "${oci_bin}" os object put --config-file "${OCI_CONFIG}" --profile "${OCI_PROFILE}" \
        --region "${OCI_REGION}" --namespace-name "${NAMESPACE}" --bucket-name "${BUCKET}" \
        --name "${object}" --file "${archive}" --force >/dev/null
    "${oci_bin}" os object put --config-file "${OCI_CONFIG}" --profile "${OCI_PROFILE}" \
        --region "${OCI_REGION}" --namespace-name "${NAMESPACE}" --bucket-name "${BUCKET}" \
        --name "${object}.sha256" --file "${checksum_file}" --force >/dev/null
    printf 'uploaded_object=%s\nuploaded_checksum=%s\n' "${object}" "${object}.sha256"
}

case "${ACTION}" in
    status|plan)
        exec "${REPO_ROOT}/scripts/oci-backup-status" "${ACTION}"
        ;;
    upload)
        # Run the complete local backup workflow first so the OCI archive
        # includes fresh Gitea and OpenTofu state artifacts, not just the
        # Pimox inventory.
        # OCI Object Storage is the active offsite destination. Do not let a
        # retired SSH target from the Debian backup timer add latency or
        # misleading warnings to this upload workflow.
        HOMELAB_BACKUP_SKIP_OFFSITE=true "${REPO_ROOT}/jeannie" backup
        archive="$(latest_archive)"
        [[ -n "${archive}" ]] || { echo "No encrypted archive was created." >&2; exit 1; }
        upload_archive "${archive}"
        ;;
    restore-verify)
        printf 'restore_verification=starting\n'
        object="$(${oci_bin} os object list --config-file "${OCI_CONFIG}" --profile "${OCI_PROFILE}" \
            --region "${OCI_REGION}" --namespace-name "${NAMESPACE}" --bucket-name "${BUCKET}" \
            --prefix "${PREFIX%/}/homelab-pimox-profile-" --all \
            --query 'data[?ends_with(name, `.tgz.age`)].{name:name,modified:"time-modified"}' --output json |
            python3 -c 'import json,sys; items=json.load(sys.stdin); print(max(items, key=lambda x: x.get("modified") or "").get("name", "") if items else "")')"
        if [[ -z "${object}" || "${object}" == "null" ]]; then
            echo "restore_verification=failed reason=no-encrypted-archive" >&2
            exit 1
        fi
        printf 'restore_object=%s\n' "${object}"
        tmpdir="$(mktemp -d)"
        trap 'rm -rf "${tmpdir}"' EXIT
        "${oci_bin}" os object get --config-file "${OCI_CONFIG}" --profile "${OCI_PROFILE}" \
            --region "${OCI_REGION}" --namespace-name "${NAMESPACE}" --bucket-name "${BUCKET}" \
            --name "${object}" --file "${tmpdir}/archive.tgz.age" >/dev/null
        "${oci_bin}" os object get --config-file "${OCI_CONFIG}" --profile "${OCI_PROFILE}" \
            --region "${OCI_REGION}" --namespace-name "${NAMESPACE}" --bucket-name "${BUCKET}" \
            --name "${object}.sha256" --file "${tmpdir}/archive.sha256" >/dev/null
        if ! (cd "${tmpdir}" && sha256sum -c archive.sha256); then
            echo 'restore_verification=failed reason=checksum-mismatch' >&2
            exit 1
        fi
        restore_dir="${tmpdir}/restored"
        mkdir -p "${restore_dir}"
        if ! age -d -i "${AGE_KEY_FILE}" "${tmpdir}/archive.tgz.age" |
            tar -xzf - -C "${restore_dir}" --no-same-owner --no-same-permissions; then
            echo 'restore_verification=failed reason=decrypt-or-extract' >&2
            exit 1
        fi
        if [[ ! -s "${restore_dir}/gitea/latest-gitea-backup.zip" ]]; then
            echo 'restore verification failed: Gitea backup is missing from archive.' >&2
            echo 'restore_verification=failed reason=missing-gitea-backup' >&2
            exit 1
        fi
        if ! find "${restore_dir}/tofu-state" -type f -print -quit 2>/dev/null | grep -q .; then
            echo 'restore verification failed: OpenTofu state is missing from archive.' >&2
            echo 'restore_verification=failed reason=missing-tofu-state' >&2
            exit 1
        fi
        printf 'restore_verification=ok\nobject=%s\nrestored_artifacts=gitea,tofu-state\n' "${object}"
        ;;
esac
