#!/usr/bin/env bash
# Wrapper that re-points the wg-pki issuer script's relative-path
# assumption (PWD-derived publish dir, $REPO_ROOT/issued/) to the
# absolute /var/lib/wg-pki/issued/ that the bootstrap service uses.
#
# wg-pki ships the actual issuer at
# /home/max/.env/wg-pki/scripts/issue-cis490-client-cert.sh, which
# computes paths relative to its own location. This wrapper sets
# WG_PKI_STATE so the CA key is found in /var/lib/wg-pki, and forces
# --out-dir to a path under /var/lib so cis490-bootstrap (with
# ProtectHome=tmpfs) can write the resulting tarballs.

set -euo pipefail

# Resolve issuer path: prefer the install-time copy at /opt/wg-pki/,
# fall back to whatever wg-pki clone the operator has under /home.
ISSUER="${WG_PKI_ISSUER:-}"
if [[ -z "$ISSUER" ]]; then
    for cand in \
        /opt/wg-pki/scripts/issue-cis490-client-cert.sh \
        /home/max/wg-pki/scripts/issue-cis490-client-cert.sh \
        /home/max/.env/wg-pki/scripts/issue-cis490-client-cert.sh; do
        if [[ -x "$cand" ]]; then ISSUER="$cand"; break; fi
    done
fi
if [[ -z "$ISSUER" || ! -x "$ISSUER" ]]; then
    echo "wrapper: no issue-cis490-client-cert.sh found; tried /opt/wg-pki, /home/max/wg-pki, /home/max/.env/wg-pki" >&2
    exit 2
fi
OUT_ROOT="/var/lib/wg-pki/issued"

if [[ $# -lt 1 ]]; then
    echo "usage: $0 <host_id> [--out-dir DIR] [--days N]" >&2
    exit 2
fi

HOST_ID="$1"; shift

# Pull off any --out-dir already passed; we override.
EXTRA=()
while [[ $# -gt 0 ]]; do
    case "$1" in
        --out-dir) shift 2 ;;          # drop, we set it ourselves
        *) EXTRA+=("$1"); shift ;;
    esac
done

mkdir -p "$OUT_ROOT/$HOST_ID"
exec env WG_PKI_STATE=/var/lib/wg-pki \
    "$ISSUER" "$HOST_ID" --out-dir "$OUT_ROOT/$HOST_ID" "${EXTRA[@]}"
