#!/usr/bin/env bash
set -euo pipefail
source_file=${SSL_NEXUS_VENDOR_ACL_SOURCE:-/var/lib/ssl-nexus/vendor-acl.desired}
target=${SSL_NEXUS_VENDOR_ACL_TARGET:-/etc/nginx/ssl-nexus-vendor-acl.conf}
nginx_bin=${SSL_NEXUS_NGINX_BIN:-nginx}
systemctl_bin=${SSL_NEXUS_SYSTEMCTL_BIN:-systemctl}
target_dir=$(dirname "$target")
install -d -m 0755 "$target_dir"
tmp=$(mktemp "$target_dir/.ssl-nexus-vendor-acl.XXXXXX")
old=$(mktemp "$target_dir/.ssl-nexus-vendor-acl-old.XXXXXX")
cleanup(){ rm -f "$tmp" "$old"; }
trap cleanup EXIT
[[ -f "$target" ]] && cp -p "$target" "$old" || : > "$old"
if [[ -f "$source_file" ]]; then
  python3 - "$source_file" "$tmp" <<'PY'
import ipaddress, pathlib, sys
source, target = map(pathlib.Path, sys.argv[1:])
rules=[]
for number, raw in enumerate(source.read_text().splitlines(), 1):
    value=raw.strip()
    if not value: continue
    try: network=ipaddress.ip_network(value, strict=False)
    except ValueError as exc: raise SystemExit(f"invalid vendor ACL at line {number}: {exc}")
    rules.append(f"allow {network};")
target.write_text("\n".join(sorted(set(rules))) + ("\n" if rules else "") + "deny all;\n")
PY
else
  printf 'deny all;\n' > "$tmp"
fi
chmod 0644 "$tmp"
mv -f "$tmp" "$target"
if ! "$nginx_bin" -t; then
  if [[ -s "$old" ]]; then cp -p "$old" "$target"; else printf 'deny all;\n' > "$target"; fi
  "$nginx_bin" -t || true
  exit 1
fi
if "$systemctl_bin" is-active --quiet nginx; then
  "$systemctl_bin" reload nginx
fi
