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

if [[ "$(uname -s)" != "Darwin" ]]; then
  echo "Gatekeeper validation is macOS-only" >&2
  exit 2
fi

ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
TARGET="${1:-}"
MOUNT_DIR=""

if [[ -z "$TARGET" ]]; then
  TARGET="$(find "$ROOT_DIR/desktop/src-tauri/target" -name "*.dmg" -type f -print 2>/dev/null | sort | tail -n 1)"
fi

if [[ -z "$TARGET" || ! -e "$TARGET" ]]; then
  echo "usage: ./check-gatekeeper.sh [path-to-app-or-dmg]" >&2
  exit 2
fi

cleanup() {
  if [[ -n "$MOUNT_DIR" ]]; then
    hdiutil detach "$MOUNT_DIR" -quiet >/dev/null 2>&1 || true
  fi
}
trap cleanup EXIT

APP_PATH="$TARGET"
if [[ "$TARGET" == *.dmg ]]; then
  MOUNT_DIR="$(mktemp -d "${TMPDIR:-/tmp}/rho-dmg-mount.XXXXXX")"
  hdiutil attach "$TARGET" -mountpoint "$MOUNT_DIR" -nobrowse -quiet
  APP_PATH="$(find "$MOUNT_DIR" -maxdepth 2 -name "*.app" -type d -print | head -n 1)"
fi

if [[ -z "$APP_PATH" || ! -d "$APP_PATH" ]]; then
  echo "could not find .app to validate" >&2
  exit 1
fi

if xattr -lr "$APP_PATH" 2>/dev/null | grep -E "com.apple.(quarantine|provenance)" >/dev/null; then
  echo "app has quarantine/provenance extended attributes" >&2
  exit 1
fi

find "$APP_PATH/Contents" -type f -perm -111 -print0 \
  | while IFS= read -r -d '' file; do
      codesign --verify --verbose=2 "$file" >/dev/null
    done

codesign --verify --deep --strict --verbose=2 "$APP_PATH"
spctl --assess --type exec --verbose "$APP_PATH"

if [[ "$TARGET" == *.dmg ]]; then
  codesign --verify --verbose=2 "$TARGET"
  spctl --assess --type open --context context:primary-signature --verbose "$TARGET"
fi
