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

Scripts/ci/check-release-config.sh app-store

build_number="${BUILD_NUMBER:?BUILD_NUMBER is required}"
distribute_external="${TESTFLIGHT_DISTRIBUTE_EXTERNAL:-false}"
testflight_groups="${TESTFLIGHT_GROUPS:-}"
testflight_internal_group="${TESTFLIGHT_INTERNAL_GROUP:-Internal}"
uses_non_exempt="${IOS_USES_NON_EXEMPT_ENCRYPTION:-false}"
wait_processing_timeout="${TESTFLIGHT_WAIT_PROCESSING_TIMEOUT_SECONDS:-7200}"

if [[ -z "$distribute_external" ]]; then
  distribute_external="false"
fi
if [[ -z "$uses_non_exempt" ]]; then
  uses_non_exempt="false"
fi
case "$wait_processing_timeout" in
  ""|*[!0-9]*)
    echo "::error ::TESTFLIGHT_WAIT_PROCESSING_TIMEOUT_SECONDS must be an integer number of seconds." >&2
    exit 1
    ;;
esac

api_key_json="$(mktemp "${RUNNER_TEMP:-/tmp}/burrow-appstore-api-key.XXXXXX.json")"
key_file="$(mktemp "${RUNNER_TEMP:-/tmp}/burrow-appstore-key.XXXXXX.p8")"
cleanup() {
  rm -f "$api_key_json" "$key_file"
}
trap cleanup EXIT

if [[ -n "${ASC_API_KEY_PATH:-}" && -f "${ASC_API_KEY_PATH:-}" ]]; then
  cp "$ASC_API_KEY_PATH" "$key_file"
else
  printf '%s' "$ASC_API_KEY_BASE64" | base64 --decode > "$key_file"
fi

KEY_FILE="$key_file" nix develop .#ci -c python3 -c 'import json, os, pathlib; print(json.dumps({"key_id": os.environ["ASC_API_KEY_ID"], "issuer_id": os.environ["ASC_API_ISSUER_ID"], "key": pathlib.Path(os.environ["KEY_FILE"]).read_text(), "duration": 1200, "in_house": False}))' > "$api_key_json"

args=(
  run pilot
  "api_key_path:${api_key_json}"
  "app_identifier:${BURROW_APPLE_BUNDLE_ID:-net.burrow.app}"
  "app_platform:ios"
  "distribute_only:true"
  "build_number:${build_number}"
  "wait_processing_interval:30"
  "wait_processing_timeout_duration:${wait_processing_timeout}"
  "distribute_external:${distribute_external}"
  "uses_non_exempt_encryption:${uses_non_exempt}"
)

if [[ -n "$testflight_groups" ]]; then
  args+=("groups:${testflight_groups}")
elif [[ "$distribute_external" != "true" && -n "$testflight_internal_group" ]]; then
  args+=("groups:${testflight_internal_group}")
fi

nix run nixpkgs#fastlane -- "${args[@]}"
