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

usage() {
  cat <<USAGE
Usage:
  scripts/apk/verify-release.sh [--base-url https://dewemoji.com/downloads]
USAGE
}

base_url="https://dewemoji.com/downloads"
while [[ $# -gt 0 ]]; do
  case "$1" in
    --base-url) base_url="$2"; shift 2 ;;
    -h|--help) usage; exit 0 ;;
    *) echo "error: unknown argument '$1'" >&2; usage; exit 1 ;;
  esac
done

version_url="${base_url%/}/version.json"
apk_url="${base_url%/}/dewemoji-latest.apk"

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

version_file="${tmp_dir}/version.json"
apk_file="${tmp_dir}/dewemoji-latest.apk"

echo "== Fetch version metadata =="
curl -fsSL "${version_url}" -o "${version_file}"
python3 - <<PY
import json
from pathlib import Path

obj = json.loads(Path("${version_file}").read_text(encoding="utf-8"))
required = ["appId", "channel", "versionName", "versionCode", "apkUrl", "sha256", "publishedAt"]
missing = [k for k in required if k not in obj]
if missing:
    raise SystemExit(f"error: missing fields in version.json: {', '.join(missing)}")

print(f"versionName={obj['versionName']}")
print(f"versionCode={obj['versionCode']}")
print(f"apkUrl={obj['apkUrl']}")
print(f"sha256={obj['sha256']}")
PY

echo "== Download latest APK =="
curl -fL "${apk_url}" -o "${apk_file}"

local_sha="$(shasum -a 256 "${apk_file}" | awk '{print $1}')"
expected_sha="$(python3 - <<PY
import json
from pathlib import Path
obj = json.loads(Path("${version_file}").read_text(encoding="utf-8"))
print(obj["sha256"])
PY
)"

echo "local_sha=${local_sha}"
echo "expected_sha=${expected_sha}"

if [[ "${local_sha}" != "${expected_sha}" ]]; then
  echo "error: checksum mismatch" >&2
  exit 1
fi

echo "OK: release metadata and APK checksum are consistent"
