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

TEAM_ID="${APPSOK_TEAM_ID:-AWA82DP9WD}"
IDENTITY="${APPSOK_SIGN_IDENTITY:-Developer ID Application: Dongmyung Lee ($TEAM_ID)}"
AGE_KEY="${APPSOK_SOPS_AGE_KEY_FILE:-$HOME/.config/sops/age/appsok-ci-key.txt}"
SECRET_FILE="${APPSOK_CI_SECRET_FILE:-secrets/appsok.ci.sops.json}"

export PATH="$HOME/SDK/flutter/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"

cd "$(git rev-parse --show-toplevel 2>/dev/null || pwd)"

need() {
  if ! command -v "$1" >/dev/null 2>&1; then
    echo "missing command: $1" >&2
    exit 1
  fi
}

need codesign
need ditto
need flutter
need python3
need security
need shasum
need sops
need spctl
need xcrun

if [ ! -f "$AGE_KEY" ]; then
  echo "missing SOPS age key: $AGE_KEY" >&2
  exit 1
fi

if [ ! -f "$SECRET_FILE" ]; then
  echo "missing encrypted CI secret file: $SECRET_FILE" >&2
  exit 1
fi

export SOPS_AGE_KEY_FILE="$AGE_KEY"

read_secret() {
  local key="$1"
  sops -d "$SECRET_FILE" | python3 -c "import json, sys; print(json.load(sys.stdin)['$key'])"
}

KEYCHAIN_PASSWORD="$(read_secret keychain_password)"
NOTARY_PROFILE="$(read_secret notary_profile)"

APP_PATH="build/macos/Build/Products/Release/AppSok.app"
ADB_PATH="$APP_PATH/Contents/Resources/adb-runtime/adb"
NOTARY_ZIP="build/macos/Build/Products/Release/AppSok-notary.zip"
FINAL_ZIP="build/macos/Build/Products/Release/AppSok-certified.zip"
FINAL_SHA256="$FINAL_ZIP.sha256"

security unlock-keychain -p "$KEYCHAIN_PASSWORD" "$HOME/Library/Keychains/login.keychain-db"
security set-keychain-settings -lut 21600 "$HOME/Library/Keychains/login.keychain-db"
security set-key-partition-list \
  -S apple-tool:,apple:,codesign: \
  -s \
  -k "$KEYCHAIN_PASSWORD" \
  "$HOME/Library/Keychains/login.keychain-db" >/dev/null

flutter pub get
flutter analyze
flutter test
flutter build macos

codesign --force --options runtime --timestamp --sign "$IDENTITY" "$ADB_PATH"
codesign --verify --strict --verbose=2 "$ADB_PATH"

codesign \
  --force \
  --deep \
  --options runtime \
  --timestamp \
  --entitlements macos/Runner/Release.entitlements \
  --sign "$IDENTITY" \
  "$APP_PATH"
codesign --verify --deep --strict --verbose=2 "$APP_PATH"

rm -f "$NOTARY_ZIP" "$FINAL_ZIP" "$FINAL_SHA256"
ditto -c -k --keepParent "$APP_PATH" "$NOTARY_ZIP"

xcrun notarytool submit "$NOTARY_ZIP" --keychain-profile "$NOTARY_PROFILE" --wait
xcrun stapler staple -v "$APP_PATH"
spctl --assess --type execute --verbose=4 "$APP_PATH"

ditto -c -k --keepParent "$APP_PATH" "$FINAL_ZIP"
shasum -a 256 "$FINAL_ZIP" | tee "$FINAL_SHA256"
ls -lh "$FINAL_ZIP"
ls -lh "$FINAL_SHA256"
