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

repo_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "$repo_root"

signing_ready=0
keychain_path=""

write_env() {
  local key="$1"
  local value="$2"
  if [[ -n "${GITHUB_ENV:-}" ]]; then
    echo "${key}=${value}" >> "$GITHUB_ENV"
  fi
}

install_profile_file() {
  local source="$1"
  [[ -f "$source" ]] || return 0

  local uuid
  uuid="$(security cms -D -i "$source" 2>/dev/null | plutil -extract UUID raw -o - - 2>/dev/null || true)"
  if [[ -z "$uuid" ]]; then
    uuid="$(basename "$source")"
  fi

  local profiles_dir="$HOME/Library/MobileDevice/Provisioning Profiles"
  mkdir -p "$profiles_dir"
  cp "$source" "${profiles_dir}/${uuid}.provisionprofile"
  echo "Installed provisioning profile ${uuid}."
}

install_profile_base64() {
  local name="$1"
  local value="${!name:-}"
  [[ -n "$value" ]] || return 0

  local out="${RUNNER_TEMP:-/tmp}/${name}.provisionprofile"
  printf '%s' "$value" | base64 --decode > "$out"
  install_profile_file "$out"
}

install_profile_env_path() {
  local name="$1"
  local path="${!name:-}"
  [[ -n "$path" ]] || return 0
  if [[ ! -f "$path" ]]; then
    echo "::error ::${name} points to a missing provisioning profile: ${path}" >&2
    exit 1
  fi
  install_profile_file "$path"
}

for profile in \
  Apple/Profiles/*.provisionprofile \
  Apple/Profiles/*.mobileprovision \
  .forgejo/actions/export/*.provisionprofile \
  .forgejo/actions/export/*.mobileprovision; do
  [[ -e "$profile" ]] || continue
  install_profile_file "$profile"
done
install_profile_env_path APPLE_PROVISIONING_PROFILE_PATH
install_profile_env_path APPLE_NETWORK_EXTENSION_PROVISIONING_PROFILE_PATH
install_profile_env_path APPLE_MACOS_PROVISIONING_PROFILE_PATH
install_profile_base64 APPLE_PROVISIONING_PROFILE_BASE64
install_profile_base64 APPLE_NETWORK_EXTENSION_PROVISIONING_PROFILE_BASE64
install_profile_base64 APPLE_MACOS_PROVISIONING_PROFILE_BASE64

cert_base64="${APPLE_SIGNING_CERTIFICATE_BASE64:-${APPLE_DISTRIBUTION_CERTIFICATE_BASE64:-}}"
cert_path_env="${APPLE_SIGNING_CERTIFICATE_PATH:-${APPLE_DISTRIBUTION_CERTIFICATE_PATH:-}}"
cert_password="${APPLE_SIGNING_CERTIFICATE_PASSWORD:-${APPLE_DISTRIBUTION_CERTIFICATE_PASSWORD:-}}"
keychain_password="${APPLE_KEYCHAIN_PASSWORD:-${cert_password}}"

if [[ -n "$cert_base64" || -n "$cert_path_env" ]]; then
  if [[ -z "$cert_password" ]]; then
    echo "::error ::APPLE_SIGNING_CERTIFICATE_PASSWORD is required when Apple signing certificate material is set." >&2
    exit 1
  fi

  cert_path="${RUNNER_TEMP:-/tmp}/burrow-apple-signing.p12"
  keychain_path="$HOME/Library/Keychains/BurrowRelease.keychain-db"
  if [[ -n "$cert_path_env" ]]; then
    if [[ ! -f "$cert_path_env" ]]; then
      echo "::error ::APPLE_SIGNING_CERTIFICATE_PATH points to a missing file: ${cert_path_env}" >&2
      exit 1
    fi
    cp "$cert_path_env" "$cert_path"
  else
    printf '%s' "$cert_base64" | base64 --decode > "$cert_path"
  fi

  security create-keychain -p "$keychain_password" "$keychain_path" || true
  security set-keychain-settings -lut 21600 "$keychain_path"
  security unlock-keychain -p "$keychain_password" "$keychain_path"
  security import "$cert_path" \
    -k "$keychain_path" \
    -P "$cert_password" \
    -T /usr/bin/codesign \
    -T /usr/bin/security \
    -T /usr/bin/productbuild \
    -T /Applications/Xcode.app/Contents/Developer/usr/bin/xcodebuild
  security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$keychain_password" "$keychain_path" >/dev/null

  existing="$(security list-keychains -d user | sed 's/[ "]//g' || true)"
  if ! printf '%s\n' "$existing" | grep -Fxq "$keychain_path"; then
    security list-keychains -d user -s "$keychain_path" $existing
  fi

  signing_ready=1
  write_env BURROW_APPLE_KEYCHAIN_PATH "$keychain_path"
else
  identities="$(security find-identity -v -p codesigning 2>/dev/null || true)"
  if printf '%s\n' "$identities" | grep -Eq '"(Apple Distribution|Developer ID Application):'; then
    signing_ready=1
  fi
fi

write_env BURROW_APPLE_SIGNING_READY "$signing_ready"
if [[ "$signing_ready" == "1" ]]; then
  echo "Apple signing assets are available."
else
  echo "::notice ::Apple signing certificate is not configured; release lane will build unsigned validation artifacts only."
fi
