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

usage() {
  cat <<USAGE
Usage:
  scripts/apk/publish-r2.sh \
    --apk /path/to/dewemoji-v1.1.2-112.apk \
    --version-name 1.1.2 \
    --version-code 112 \
    [--notes "Release notes"] \
    [--min-supported-version-code 100] \
    [--force false]

Required env:
  R2_ACCOUNT_ID
  R2_ACCESS_KEY_ID
  R2_SECRET_ACCESS_KEY
  R2_BUCKET
Optional env:
  R2_PUBLIC_BASE_URL (example: https://downloads.dewemoji.com)
  DEWEMOJI_APK_URL (default: https://dewemoji.com/downloads/dewemoji-latest.apk)
  APK_VERSIONED_CACHE_CONTROL (default: public,max-age=31536000,immutable)
  APK_LATEST_CACHE_CONTROL (default: no-store,max-age=0,must-revalidate)
  APK_VERSION_JSON_CACHE_CONTROL (default: no-store,max-age=0,must-revalidate)
USAGE
}

for required in R2_ACCOUNT_ID R2_ACCESS_KEY_ID R2_SECRET_ACCESS_KEY R2_BUCKET; do
  if [[ -z "${!required:-}" ]]; then
    echo "error: missing env ${required}" >&2
    exit 1
  fi
done

if ! command -v aws >/dev/null 2>&1; then
  echo "error: aws cli is required" >&2
  exit 1
fi

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
MAKE_VERSION_SCRIPT="${ROOT_DIR}/scripts/apk/make-version-json.sh"

apk=""
version_name=""
version_code=""
notes=""
min_supported_version_code="100"
force="false"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --apk) apk="$2"; shift 2 ;;
    --version-name) version_name="$2"; shift 2 ;;
    --version-code) version_code="$2"; shift 2 ;;
    --notes) notes="$2"; shift 2 ;;
    --min-supported-version-code) min_supported_version_code="$2"; shift 2 ;;
    --force) force="$2"; shift 2 ;;
    -h|--help) usage; exit 0 ;;
    *) echo "error: unknown argument '$1'" >&2; usage; exit 1 ;;
  esac
done

if [[ -z "${apk}" || -z "${version_name}" || -z "${version_code}" ]]; then
  echo "error: --apk, --version-name, and --version-code are required" >&2
  usage
  exit 1
fi

if [[ ! -f "${apk}" ]]; then
  echo "error: apk file not found: ${apk}" >&2
  exit 1
fi

endpoint="https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com"
export AWS_ACCESS_KEY_ID="${R2_ACCESS_KEY_ID}"
export AWS_SECRET_ACCESS_KEY="${R2_SECRET_ACCESS_KEY}"

tmp_dir="$(mktemp -d)"
trap 'rm -rf "${tmp_dir}"' EXIT

sha256="$(shasum -a 256 "${apk}" | awk '{print $1}')"
versioned_key="apk/dewemoji-v${version_name}-${version_code}.apk"
latest_key="apk/dewemoji-latest.apk"
version_json_key="apk/version.json"

apk_url="${DEWEMOJI_APK_URL:-https://dewemoji.com/downloads/dewemoji-latest.apk}"
versioned_cache_control="${APK_VERSIONED_CACHE_CONTROL:-public,max-age=31536000,immutable}"
latest_cache_control="${APK_LATEST_CACHE_CONTROL:-no-store,max-age=0,must-revalidate}"
version_json_cache_control="${APK_VERSION_JSON_CACHE_CONTROL:-no-store,max-age=0,must-revalidate}"
version_json_path="${tmp_dir}/version.json"
"${MAKE_VERSION_SCRIPT}" \
  --version-name "${version_name}" \
  --version-code "${version_code}" \
  --sha256 "${sha256}" \
  --notes "${notes}" \
  --apk-url "${apk_url}" \
  --min-supported-version-code "${min_supported_version_code}" \
  --force "${force}" \
  --out "${version_json_path}"

echo "== Upload versioned APK =="
aws --endpoint-url "${endpoint}" s3 cp "${apk}" "s3://${R2_BUCKET}/${versioned_key}" \
  --content-type application/vnd.android.package-archive \
  --cache-control "${versioned_cache_control}"

echo "== Upload latest APK alias =="
aws --endpoint-url "${endpoint}" s3 cp "${apk}" "s3://${R2_BUCKET}/${latest_key}" \
  --content-type application/vnd.android.package-archive \
  --cache-control "${latest_cache_control}"

echo "== Upload version metadata =="
aws --endpoint-url "${endpoint}" s3 cp "${version_json_path}" "s3://${R2_BUCKET}/${version_json_key}" \
  --content-type application/json \
  --cache-control "${version_json_cache_control}"

echo "Published to R2 bucket: ${R2_BUCKET}"
echo "Versioned APK key: ${versioned_key}"
echo "Latest APK key: ${latest_key}"
echo "Version JSON key: ${version_json_key}"

if [[ -n "${R2_PUBLIC_BASE_URL:-}" ]]; then
  base="${R2_PUBLIC_BASE_URL%/}"
  echo "Public versioned APK URL: ${base}/${versioned_key}"
  echo "Public latest APK URL: ${base}/${latest_key}"
  echo "Public version JSON URL: ${base}/${version_json_key}"
fi
