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

KEYDIR="/var/lib/cmkpush/.ssh"
KEYFILE="$KEYDIR/id_cmk-agent-bootstrap"

force=false
if [[ "${1:-}" == "--force" ]]; then
  force=true
fi

# Ensure directory exists (you said postinst does, but this makes it bulletproof)
install -d -m 0700 "$KEYDIR"

# In force mode, remove existing keypair first -> ssh-keygen will never prompt
if $force; then
  rm -f "$KEYFILE" "$KEYFILE.pub"
fi

# Create only if missing
if [[ ! -f "$KEYFILE" || ! -f "$KEYFILE.pub" ]]; then
  ssh-keygen -t ed25519 -f "$KEYFILE" -N "" -q
  chmod 600 "$KEYFILE"
  chmod 644 "$KEYFILE.pub"
fi

PUBKEY="$(cat "$KEYFILE.pub")"

# Output one authorized_keys line (replace <fqdn> later or pass it in)
echo "restrict,command=\"/usr/bin/cmk-push-agent-reg\" $PUBKEY" > $KEYDIR/cmk-agent-deploy-key
