#!/bin/bash
# One-time: create a STABLE self-signed code-signing identity for the audio daemon.
# Why: a TCC microphone grant is keyed to the binary's signing identity. An ad-hoc
# signature is cdhash-based, so it changes on every rebuild and the user would have
# to re-grant the mic each time. A self-signed cert gives a stable identity, so the
# grant persists across rebuilds. Fully non-interactive: we own a dedicated keychain
# with a known password, so codesign never has to prompt for keychain access.
set -e
IDENT="SkyKoi Audio Daemon"
DIR="$HOME/.skykoi/codesign"
KC="$DIR/skykoi-codesign.keychain-db"
PW="skykoi-codesign"
mkdir -p "$DIR"

if security find-certificate -c "$IDENT" "$KC" >/dev/null 2>&1; then
  echo "setup-codesign: identity already exists ✓"
else
  # self-signed cert with the codeSigning EKU
  openssl req -x509 -newkey rsa:2048 -nodes -days 7300 \
    -keyout "$DIR/key.pem" -out "$DIR/cert.pem" \
    -subj "/CN=$IDENT" \
    -addext "basicConstraints=critical,CA:FALSE" \
    -addext "keyUsage=critical,digitalSignature" \
    -addext "extendedKeyUsage=critical,codeSigning" >/dev/null 2>&1
  openssl pkcs12 -export -inkey "$DIR/key.pem" -in "$DIR/cert.pem" \
    -out "$DIR/id.p12" -passout "pass:$PW" -name "$IDENT" >/dev/null 2>&1
  security create-keychain -p "$PW" "$KC" 2>/dev/null || true
  security unlock-keychain -p "$PW" "$KC"
  security set-keychain-settings "$KC"   # no auto-lock timeout
  security import "$DIR/id.p12" -k "$KC" -P "$PW" -A -T /usr/bin/codesign >/dev/null 2>&1
  # let codesign use the private key without a GUI prompt (we know the password)
  security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$PW" "$KC" >/dev/null 2>&1 || true
  rm -f "$DIR/key.pem" "$DIR/cert.pem" "$DIR/id.p12"
  echo "setup-codesign: created self-signed identity ✓"
fi

# make sure the keychain is in the search list + unlocked so build.sh can find the identity
if ! security list-keychains -d user | tr -d '" ' | grep -qx "$KC"; then
  security list-keychains -d user -s "$KC" $(security list-keychains -d user | sed -e 's/^[[:space:]]*"//' -e 's/"$//')
fi
security unlock-keychain -p "$PW" "$KC" 2>/dev/null || true
security find-identity -v -p codesigning "$KC" | grep -q "$IDENT" \
  && echo "setup-codesign: identity usable for codesigning ✓" \
  || echo "setup-codesign: WARNING identity not found by codesign — build will fall back to ad-hoc"
