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

SRC_DIR="${WDVPX_SRC_DIR:-/Users/van/Dropbox/public_html/wdv-px}"
APP_DIR="${WDVPX_APP_DIR:-$HOME/Applications/wdv-px.app}"
SIGN_ID="${WDVPX_SIGN_ID:--}"
USE_SANDBOX="${WDVPX_SANDBOX:-1}"
UNIVERSAL="${WDVPX_UNIVERSAL:-0}"
APP_VER="${WDVPX_VERSION:-1.0.0}"
BUILD_NUM="${WDVPX_BUILD:-1}"
SCRATCH="/tmp/wdv-px-build"
ISET_DIR="$SCRATCH/wdv-px.iconset"
LAUNCH=1

if [[ "${1:-}" == "--no-launch" ]]; then
  LAUNCH=0
fi

mkdir -p "$APP_DIR/Contents/MacOS" "$APP_DIR/Contents/Resources" "$ISET_DIR"

# 1. Generate 100x100 web icon.png and Retina wdv-px.icns
clang -arch arm64 -mmacosx-version-min=14.0 -O2 -Wall -Wextra -fobjc-arc \
  -framework Cocoa -framework ImageIO \
  "$SRC_DIR/mkicon.m" -o "$SCRATCH/mkicon"

"$SCRATCH/mkicon" "$SRC_DIR/icon.png" "$ISET_DIR"
iconutil -c icns "$ISET_DIR" -o "$APP_DIR/Contents/Resources/wdv-px.icns"
cp "$SRC_DIR/PrivacyInfo.xcprivacy" "$APP_DIR/Contents/Resources/PrivacyInfo.xcprivacy"

# 2. Detect SDK/OS metadata for Mac App Store compatibility
OS_BUILD="$(sw_vers -buildVersion 2>/dev/null || echo 25A000)"
SDK_VER="$(xcrun --show-sdk-version 2>/dev/null || echo 15.0)"
SDK_BUILD="$(xcrun --show-sdk-build-version 2>/dev/null || echo "$OS_BUILD")"

cat <<PLIST > "$APP_DIR/Contents/Info.plist"
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>CFBundleExecutable</key><string>wdv-px</string>
  <key>CFBundleIdentifier</key><string>com.wdv.wdv-px</string>
  <key>CFBundleName</key><string>wdv-px</string>
  <key>CFBundleDisplayName</key><string>wdv-px</string>
  <key>CFBundleIconFile</key><string>wdv-px</string>
  <key>CFBundlePackageType</key><string>APPL</string>
  <key>CFBundleShortVersionString</key><string>${APP_VER}</string>
  <key>CFBundleVersion</key><string>${BUILD_NUM}</string>
  <key>LSApplicationCategoryType</key><string>public.app-category.utilities</string>
  <key>LSMinimumSystemVersion</key><string>14.0</string>
  <key>NSPrincipalClass</key><string>NSApplication</string>
  <key>NSHighResolutionCapable</key><true/>
  <key>NSHumanReadableCopyright</key><string>Copyright © 2026 L Van Warren (Warren Design Vision). All rights reserved.</string>
  <key>NSScreenCaptureUsageDescription</key><string>wdv-px captures the pixel region framed by its floating ruler template.</string>
  <key>BuildMachineOSBuild</key><string>${OS_BUILD}</string>
  <key>DTPlatformName</key><string>macosx</string>
  <key>ITSAppUsesNonExemptEncryption</key><false/>
  <key>DTCompiler</key><string>com.apple.compilers.llvm.clang.1_0</string>
  <key>DTPlatformVersion</key><string>${SDK_VER}</string>
  <key>DTPlatformBuild</key><string>${SDK_BUILD}</string>
  <key>DTSDKName</key><string>macosx${SDK_VER}</string>
  <key>DTSDKBuild</key><string>${SDK_BUILD}</string>
  <key>CFBundleURLTypes</key>
  <array>
    <dict>
      <key>CFBundleURLName</key><string>com.wdv.wdv-px.url</string>
      <key>CFBundleURLSchemes</key>
      <array>
        <string>wdv-px</string>
      </array>
    </dict>
  </array>
</dict>
</plist>
PLIST

# 3. Compile wdv-px (arm64 native or Universal arm64 + x86_64)
osascript -e 'tell application "wdv-px" to quit' 2>/dev/null || true
killall wdv-px 2>/dev/null || true

CFLAGS=(-mmacosx-version-min=14.0 -O2 -Wall -Wextra -fobjc-arc
        -framework Cocoa -framework ImageIO -framework Carbon -framework ScreenCaptureKit)

if [[ "$UNIVERSAL" -eq 1 ]]; then
  clang -arch arm64  "${CFLAGS[@]}" "$SRC_DIR/wdv-px.m" -o "$SCRATCH/wdv-px-arm64"
  clang -arch x86_64 "${CFLAGS[@]}" "$SRC_DIR/wdv-px.m" -o "$SCRATCH/wdv-px-x86_64"
  lipo -create "$SCRATCH/wdv-px-arm64" "$SCRATCH/wdv-px-x86_64" -output "$APP_DIR/Contents/MacOS/wdv-px"
else
  clang -arch arm64 "${CFLAGS[@]}" "$SRC_DIR/wdv-px.m" -o "$APP_DIR/Contents/MacOS/wdv-px"
fi

# 4. Strip quarantine attributes (mandatory for App Store Connect) and sign
/usr/bin/xattr -cr "$APP_DIR"

SIGN_ARGS=(--force --deep --sign "$SIGN_ID")
if [[ "$SIGN_ID" != "-" ]]; then
  SIGN_ARGS+=(--options runtime --timestamp)
fi
if [[ "$USE_SANDBOX" -eq 1 ]]; then
  SIGN_ARGS+=(--entitlements "$SRC_DIR/wdv-px.entitlements")
fi

codesign "${SIGN_ARGS[@]}" "$APP_DIR"
codesign --verify --deep --strict "$APP_DIR"
touch "$APP_DIR"

sips -g pixelWidth -g pixelHeight "$SRC_DIR/icon.png"

if [[ "$LAUNCH" -eq 1 ]]; then
  open "$APP_DIR"
fi
