my-homelab-configs/scripts/oci-backup-freshness

34 lines
1.7 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
oci_bin="$(command -v oci 2>/dev/null || printf '%s' "${HOME}/.local/share/homelab/venvs/oci-cli/bin/oci")"
config="${OCI_CONFIG_FILE:-${HOME}/.oci/config}"
profile="${OCI_CLI_PROFILE:-${OCI_CONFIG_PROFILE:-DEFAULT}}"
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/}"
max_hours="${LAB_OCI_BACKUP_MAX_AGE_HOURS:-36}"
[[ -n "${region}" && -n "${bucket}" ]] || { echo 'FAIL OCI backup bucket/region is not configured.'; exit 1; }
if [[ -z "${namespace}" ]]; then
namespace="$(${oci_bin} os ns get --config-file "${config}" --profile "${profile}" --region "${region}" --query data --raw-output)"
fi
latest="$(${oci_bin} os object list --config-file "${config}" --profile "${profile}" --region "${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 - "${latest}" "${max_hours}" <<'PY'
import datetime as dt, json, sys
items = json.loads(sys.argv[1])
if not items:
print("FAIL OCI backup freshness: no encrypted archive found")
raise SystemExit(1)
item = max(items, key=lambda x: x.get("modified") or "")
stamp = (item.get("modified") or "").replace("Z", "+00:00")
age = (dt.datetime.now(dt.timezone.utc) - dt.datetime.fromisoformat(stamp)).total_seconds() / 3600
print(f"latest={item['name']} age_hours={age:.1f} threshold_hours={sys.argv[2]}")
if age > float(sys.argv[2]):
print("FAIL OCI backup freshness: latest archive is stale")
raise SystemExit(1)
print("PASS OCI backup freshness")
PY