#!/usr/bin/env bash
# Build a Mac App Store uploadable .pkg for wdv-px (auto-detects certs & Team ID)
# Usage:
#   PROV_PROFILE="$HOME/Desktop/wdv-px_AppStore.provisionprofile" ./package_mas.sh
# Optional overrides:
#   APP_CERT="..." PKG_CERT="..." WDVPX_VERSION=1.0.0 WDVPX_BUILD=1 WDVPX_UNIVERSAL=1
set -euo pipefail

SRC_DIR="${WDVPX_SRC_DIR:-/Users/van/Dropbox/public_html/wdv-px}"
OUT_DIR="/tmp/wdv-px-mas"
APP_BUNDLE="$OUT_DIR/wdv-px.app"
MAS_ENT="$OUT_DIR/mas.entitlements"
VER="${WDVPX_VERSION:-1.0.0}"
BUILD_NUM="${WDVPX_BUILD:-1}"
PKG_OUT="$HOME/Desktop/wdv-px-${VER}-${BUILD_NUM}.pkg"

mkdir -p "$OUT_DIR"

# Auto-detect Mac App Store signing certificates in Keychain if not provided
if [[ -z "${APP_CERT:-}" ]]; then
  APP_CERT="$(security find-identity -v -p basic | sed -n 's/.*"\(\(Apple Distribution\|3rd Party Mac Developer Application\|Mac App Distribution\):[^"]*\)".*/\1/p' | head -n 1 || true)"
fi
if [[ -z "${PKG_CERT:-}" ]]; then
  PKG_CERT="$(security find-identity -v -p basic | sed -n 's/.*"\(\(Mac Installer Distribution\|3rd Party Mac Developer Installer\):[^"]*\)".*/\1/p' | head -n 1 || true)"
fi
if [[ -z "${PROV_PROFILE:-}" ]]; then
  PROV_PROFILE="$(ls -t "$HOME/Desktop"/*wdv*px*.provisionprofile "$HOME/Downloads"/*wdv*px*.provisionprofile 2>/dev/null | head -n 1 || true)"
fi

if [[ -z "${APP_CERT:-}" ]]; then
  echo "Error: No 'Apple Distribution' or 'Mac App Distribution' certificate found in Keychain." >&2
  exit 1
fi
if [[ -z "${PKG_CERT:-}" ]]; then
  echo "Error: No 'Mac Installer Distribution' or '3rd Party Mac Developer Installer' certificate found in Keychain." >&2
  exit 1
fi
if [[ -z "${PROV_PROFILE:-}" || ! -f "$PROV_PROFILE" ]]; then
  echo "Error: Set PROV_PROFILE=/path/to/wdv-px.provisionprofile (needed for App Store / TestFlight)." >&2
  exit 1
fi

echo "Using APP_CERT:     $APP_CERT"
echo "Using PKG_CERT:     $PKG_CERT"
echo "Using PROV_PROFILE: $PROV_PROFILE"

# Extract application-identifier and TeamIdentifier from provisioning profile and merge MAS entitlements
python3 - "$SRC_DIR/wdv-px.entitlements" "$PROV_PROFILE" "$MAS_ENT" <<'PY'
import plistlib, subprocess, sys

base_path, prof_path, out_path = sys.argv[1], sys.argv[2], sys.argv[3]
cms_xml = subprocess.check_output(["security", "cms", "-D", "-i", prof_path])
prof = plistlib.loads(cms_xml)
prof_ent = prof.get("Entitlements", {})
app_id = prof_ent.get("com.apple.application-identifier") or prof_ent.get("application-identifier")
team_id = (prof.get("TeamIdentifier") or [None])[0] or prof_ent.get("com.apple.developer.team-identifier")

if not app_id or not team_id:
    sys.exit("Error: Could not extract application-identifier / TeamIdentifier from provisioning profile.")

with open(base_path, "rb") as f:
    ent = plistlib.load(f)

ent["com.apple.application-identifier"] = app_id
ent["com.apple.developer.team-identifier"] = team_id

with open(out_path, "wb") as f:
    plistlib.dump(ent, f, fmt=plistlib.FMT_XML)

print(f"Merged MAS entitlements: app-id={app_id}, team-id={team_id}")
PY

# Build Universal sandboxed binary (default arm64 + x86_64) without launching
WDVPX_SRC_DIR="$SRC_DIR" \
WDVPX_APP_DIR="$APP_BUNDLE" \
WDVPX_SIGN_ID="$APP_CERT" \
WDVPX_SANDBOX=1 \
WDVPX_UNIVERSAL="${WDVPX_UNIVERSAL:-1}" \
WDVPX_VERSION="$VER" \
WDVPX_BUILD="$BUILD_NUM" \
"$SRC_DIR/build.sh" --no-launch

# Embed provisioning profile and stamp DTXcode + DTXcodeBuild from installed Xcode
cp "$PROV_PROFILE" "$APP_BUNDLE/Contents/embedded.provisionprofile"

if command -v xcodebuild >/dev/null 2>&1; then
  XC_OUT="$(xcodebuild -version 2>/dev/null || true)"
  XC_VER="$(awk '/^Xcode /{print $2}' <<< "$XC_OUT")"
  XC_BUILD="$(awk '/Build version/{print $3}' <<< "$XC_OUT")"
  if [[ -n "$XC_VER" ]]; then
    DTXCODE="$(python3 - "$XC_VER" <<'PY'
import sys
parts = [int(x) for x in sys.argv[1].split(".")]
while len(parts) < 3: parts.append(0)
print(f"{parts[0]:02d}{parts[1]}{parts[2]}")
PY
)"
    /usr/libexec/PlistBuddy -c "Delete :DTXcode" "$APP_BUNDLE/Contents/Info.plist" 2>/dev/null || true
    /usr/libexec/PlistBuddy -c "Add :DTXcode string $DTXCODE" "$APP_BUNDLE/Contents/Info.plist"
  fi
  if [[ -n "$XC_BUILD" ]]; then
    /usr/libexec/PlistBuddy -c "Delete :DTXcodeBuild" "$APP_BUNDLE/Contents/Info.plist" 2>/dev/null || true
    /usr/libexec/PlistBuddy -c "Add :DTXcodeBuild string $XC_BUILD" "$APP_BUNDLE/Contents/Info.plist"
  fi
fi

# Strip all extended attributes (mandatory since Feb 2025) and sign with MAS entitlements
/usr/bin/xattr -cr "$APP_BUNDLE"
plutil -lint "$APP_BUNDLE/Contents/Info.plist"
plutil -lint "$APP_BUNDLE/Contents/Resources/PrivacyInfo.xcprivacy"

codesign --force --deep --options runtime --timestamp \
  --entitlements "$MAS_ENT" \
  --sign "$APP_CERT" "$APP_BUNDLE"
codesign --verify --deep --strict --verbose=2 "$APP_BUNDLE"

productbuild \
  --component "$APP_BUNDLE" /Applications \
  --sign "$PKG_CERT" \
  "$PKG_OUT"

pkgutil --check-signature "$PKG_OUT"
echo ""
echo "Ready for upload: $PKG_OUT"
echo "Open Apple Transporter (Mac App Store), drop $PKG_OUT, click Verify, then Deliver."
