#!/bin/zsh
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PACKAGE_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$PACKAGE_DIR"

product="${1:-CairnquireSync}"
case "$product" in
  CairnquireSync)
    signing_identifier="com.cairnquire.sync"
    ;;
  cairnquire-cli)
    signing_identifier="com.cairnquire.cli"
    ;;
  *)
    echo "Unsupported product: $product" >&2
    echo "Usage: scripts/sign-dev.sh [CairnquireSync|cairnquire-cli]" >&2
    exit 2
    ;;
esac

identity="${CAIRNQUIRE_CODESIGN_IDENTITY:-}"
if [[ -z "$identity" ]]; then
  identity="$(
    security find-identity -v -p codesigning \
      | awk -F '"' '/Apple Development/ { print $2; exit }'
  )"
fi

if [[ -z "$identity" ]]; then
  echo "No Apple Development signing identity found." >&2
  echo "Create one in Xcode, then verify with:" >&2
  echo "  security find-identity -v -p codesigning" >&2
  exit 1
fi

swift build --product "$product"

executable=".build/debug/$product"
if [[ ! -f "$executable" ]]; then
  executable="$(find .build -path "*/debug/$product" -type f -perm -111 | head -n 1)"
fi

if [[ -z "$executable" || ! -f "$executable" ]]; then
  echo "Built executable not found for product: $product" >&2
  exit 1
fi

codesign \
  --force \
  --sign "$identity" \
  --identifier "$signing_identifier" \
  --timestamp=none \
  "$executable"

echo "Signed $executable"
codesign -dvvv --requirements - "$executable" 2>&1 | sed -n '1,80p'
echo
echo "Run the signed executable directly:"
echo "  $executable"
echo
echo "Avoid 'swift run $product' after signing; it can rebuild and replace the signed executable."
