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

usage() {
  cat <<USAGE
Usage:
  scripts/apk/make-version-json.sh \
    --version-name 1.1.2 \
    --version-code 112 \
    --sha256 <hex> \
    --notes "Release notes" \
    [--out ./version.json] \
    [--apk-url https://dewemoji.com/downloads/dewemoji-latest.apk] \
    [--app-id com.dewemoji.app] \
    [--channel stable] \
    [--min-supported-version-code 100] \
    [--force false]
USAGE
}

out="./version.json"
apk_url="https://dewemoji.com/downloads/dewemoji-latest.apk"
app_id="com.dewemoji.app"
channel="stable"
min_supported_version_code="100"
force="false"
version_name=""
version_code=""
sha256=""
notes=""
published_at="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"

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

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

python3 - <<PY
import json
from pathlib import Path

payload = {
    "appId": "${app_id}",
    "channel": "${channel}",
    "versionName": "${version_name}",
    "versionCode": int("${version_code}"),
    "minSupportedVersionCode": int("${min_supported_version_code}"),
    "apkUrl": "${apk_url}",
    "sha256": "${sha256}",
    "publishedAt": "${published_at}",
    "notes": "${notes}",
    "force": "${force}".lower() == "true",
}

out = Path("${out}")
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(payload, ensure_ascii=True, indent=2) + "\n", encoding="utf-8")
print(out)
PY
