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

ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
DESKTOP_DIR="$ROOT_DIR/desktop"
TAURI_DIR="$DESKTOP_DIR/src-tauri"

log() {
  printf '[rho] %s\n' "$*"
}

if [[ "$(uname -s)" != "Darwin" ]]; then
  echo "signed/notarized desktop builds are macOS-only" >&2
  exit 2
fi

if [[ -f "$ROOT_DIR/.env" ]]; then
  set -a
  # shellcheck disable=SC1091
  source "$ROOT_DIR/.env"
  set +a
fi

: "${APPLE_ID:?APPLE_ID is required}"
: "${APPLE_PASSWORD:?APPLE_PASSWORD is required}"
: "${APPLE_TEAM_ID:?APPLE_TEAM_ID is required}"

TEMP_KEYCHAIN=""
cleanup() {
  if [[ -n "$TEMP_KEYCHAIN" ]]; then
    security delete-keychain "$TEMP_KEYCHAIN" >/dev/null 2>&1 || true
  fi
}
trap cleanup EXIT

if [[ -z "${APPLE_SIGNING_IDENTITY:-}" && -n "${SIGNING_CERTIFICATE_P12_DATA:-}" ]]; then
  : "${SIGNING_CERTIFICATE_PASSWORD:?SIGNING_CERTIFICATE_PASSWORD is required when SIGNING_CERTIFICATE_P12_DATA is set}"
  KEYCHAIN_PASSWORD="${KEYCHAIN_PASSWORD:-$(uuidgen)}"
  WORK_DIR="${RUNNER_TEMP:-$ROOT_DIR/.tmp}"
  mkdir -p "$WORK_DIR"
  CERT_PATH="$WORK_DIR/rho-desktop-signing.p12"
  TEMP_KEYCHAIN="$WORK_DIR/rho-desktop-signing.keychain-db"

  log "importing signing certificate into temporary keychain"
  printf '%s' "$SIGNING_CERTIFICATE_P12_DATA" | base64 --decode > "$CERT_PATH"
  security create-keychain -p "$KEYCHAIN_PASSWORD" "$TEMP_KEYCHAIN"
  security unlock-keychain -p "$KEYCHAIN_PASSWORD" "$TEMP_KEYCHAIN"
  security import "$CERT_PATH" -k "$TEMP_KEYCHAIN" -P "$SIGNING_CERTIFICATE_PASSWORD" -T /usr/bin/codesign -T /usr/bin/security
  security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KEYCHAIN_PASSWORD" "$TEMP_KEYCHAIN"
  security list-keychains -d user -s "$TEMP_KEYCHAIN" $(security list-keychains -d user | sed 's/"//g')
fi

if [[ -z "${APPLE_SIGNING_IDENTITY:-}" ]]; then
  APPLE_SIGNING_IDENTITY="$(
    security find-identity -v -p codesigning \
      | sed -n 's/.*"\(Developer ID Application:[^"]*\)".*/\1/p' \
      | head -n 1
  )"
fi

if [[ -z "${APPLE_SIGNING_IDENTITY:-}" ]]; then
  echo "no Developer ID Application signing identity found" >&2
  exit 1
fi

log "using signing identity: $APPLE_SIGNING_IDENTITY"
security find-certificate -c "$APPLE_SIGNING_IDENTITY" -p \
  | openssl x509 -noout -checkend $((60 * 60 * 24 * 30))

if [[ ! -d "$DESKTOP_DIR/node_modules" ]]; then
  log "installing desktop npm dependencies"
  (cd "$DESKTOP_DIR" && npm install)
fi

BUILD_ARGS=(build)
if [[ -n "${TAURI_TARGET:-}" ]]; then
  BUILD_ARGS+=(--target "$TAURI_TARGET")
fi

set +e
(cd "$DESKTOP_DIR" && npm run tauri -- "${BUILD_ARGS[@]}")
status=$?
set -e

if [[ "$status" -ne 0 ]]; then
  log "Tauri packaging failed; trying fallback signed DMG builder"
  "$ROOT_DIR/scripts/create-desktop-dmg.sh" --sign "$APPLE_SIGNING_IDENTITY" --notarize
fi

if command -v xattr >/dev/null 2>&1; then
  find "$TAURI_DIR/target" \( -name "*.dmg" -o -name "*.app.tar.gz" -o -name "*.sig" \) -print0 2>/dev/null \
    | xargs -0 xattr -c 2>/dev/null || true
fi

log "signed desktop artifacts"
find "$TAURI_DIR/target" -maxdepth 8 \( -name "*.dmg" -o -name "*.app.tar.gz" -o -name "*.sig" \) -type f -print 2>/dev/null | sort || true
log "run Gatekeeper validation with: ./check-gatekeeper.sh"
