#!/usr/bin/env bash
# skcapstone-cmdb-network {apply|shadow}
#
# The one runner behind the CMDB network reconcile units (gate 4, card 075a82ce):
#   shadow  write-free scan, records a checksummed artifact
#           (skcapstone-cmdb-reconcile-shadow.service, ATLAS run-cmdb-shadow)
#   apply   writes CMDB state, records a checksummed artifact
#           (skcapstone-cmdb-reconcile-network.service through the owner-reviewed
#           launcher ~/.config/skcapstone/cmdb-network-apply, and its timer)
#
# Node data lives in one owner-reviewed targets file, never in a unit:
#   ${SKCAPSTONE_CMDB_NETWORK_TARGETS:-~/.config/skcapstone/cmdb-network-targets}
# One "HOST=skvault://REFERENCE" per line; blank lines and # comments allowed.
# The file holds skvault references, never credential values. It must be a
# regular file owned by the caller and not writable by group or others.
#
# The run goes through sk-cron-run (run ledger, alert on failure) and holds a
# non-blocking lock so a shadow and an apply never overlap each other.
set -euo pipefail

mode="${1:-}"
case "$mode" in
  apply) job="skcapstone-cmdb-reconcile-network"; extra=(--apply) ;;
  shadow) job="skcapstone-cmdb-reconcile-shadow"; extra=() ;;
  *) printf 'usage: skcapstone-cmdb-network {apply|shadow}\n' >&2; exit 64 ;;
esac

targets="${SKCAPSTONE_CMDB_NETWORK_TARGETS:-$HOME/.config/skcapstone/cmdb-network-targets}"
skcapstone="${SKCAPSTONE_BIN:-$HOME/.skenv/bin/skcapstone}"
cron_run="${SK_CRON_RUN:-$HOME/.skenv/bin/sk-cron-run}"
lock="${SKCAPSTONE_CMDB_NETWORK_LOCK:-$HOME/.skcapstone/cmdb/network-reconcile.lock}"

die() { printf 'skcapstone-cmdb-network: %s\n' "$1" >&2; exit 78; }

[ -L "$targets" ] && die "refusing symlinked targets file"
[ -f "$targets" ] || die "targets file missing: $targets"
[ "$(stat -c '%u' "$targets")" = "$(id -u)" ] || die "targets file is not owned by the caller"
perm=$(stat -c '%a' "$targets")
(( (8#$perm & 8#022) == 0 )) || die "targets file is writable by group or others"

credentials=()
declare -A seen=()
while IFS= read -r line || [ -n "$line" ]; do
  line="${line%%#*}"
  line="${line//[[:space:]]/}"
  [ -z "$line" ] && continue
  [[ "$line" =~ ^([A-Za-z0-9._-]+)=skvault://[A-Za-z0-9._/-]+$ ]] \
    || die "malformed targets line (expected HOST=skvault://REFERENCE)"
  host="${BASH_REMATCH[1]}"
  [ -z "${seen[$host]:-}" ] || die "duplicate target: $host"
  seen[$host]=1
  credentials+=(--credential "$line")
done < "$targets"
[ "${#credentials[@]}" -gt 0 ] || die "targets file names no target"

mkdir -p "$(dirname "$lock")"
exec flock --nonblock --conflict-exit-code 75 "$lock" \
  "$cron_run" "$job" "$skcapstone" cmdb reconcile --network "${extra[@]}" --record-run "${credentials[@]}"
