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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
CAPACITOR_DIR="${ROOT_DIR}/dewemoji-capacitor"
ANDROID_DIR="${ROOT_DIR}/dewemoji-capacitor/android"
APP_GRADLE="${ANDROID_DIR}/app/build.gradle"
DIST_DIR="${ROOT_DIR}/dewemoji-capacitor/dist/apk"

if [[ ! -f "${APP_GRADLE}" ]]; then
  echo "error: missing ${APP_GRADLE}" >&2
  exit 1
fi

version_name="$(awk '/versionName /{gsub(/"/, "", $2); print $2; exit}' "${APP_GRADLE}")"
version_code="$(awk '/versionCode /{print $2; exit}' "${APP_GRADLE}")"
if [[ -z "${version_name}" || -z "${version_code}" ]]; then
  echo "error: failed to read versionName/versionCode from ${APP_GRADLE}" >&2
  exit 1
fi

mkdir -p "${DIST_DIR}"

echo "== Build local web assets =="
npm --prefix "${CAPACITOR_DIR}" run build

echo "== Sync Capacitor Android project =="
(
  cd "${CAPACITOR_DIR}"
  npx --yes cap sync android
)

echo "== Build release APK =="
(
  cd "${ANDROID_DIR}"
  ./gradlew clean assembleRelease
)

unsigned_apk="${ANDROID_DIR}/app/build/outputs/apk/release/app-release-unsigned.apk"
signed_apk_default="${ANDROID_DIR}/app/build/outputs/apk/release/app-release.apk"
input_apk=""

if [[ -f "${signed_apk_default}" ]]; then
  input_apk="${signed_apk_default}"
elif [[ -f "${unsigned_apk}" ]]; then
  input_apk="${unsigned_apk}"
else
  echo "error: release APK not found under app/build/outputs/apk/release" >&2
  exit 1
fi

output_apk="${DIST_DIR}/dewemoji-v${version_name}-${version_code}.apk"

if [[ -n "${ANDROID_KEYSTORE_PATH:-}" && -n "${ANDROID_KEYSTORE_PASSWORD:-}" && -n "${ANDROID_KEY_ALIAS:-}" && -n "${ANDROID_KEY_PASSWORD:-}" ]]; then
  if ! command -v apksigner >/dev/null 2>&1; then
    echo "error: apksigner is required for signing but not found" >&2
    exit 1
  fi

  echo "== Sign APK =="
  apksigner sign \
    --ks "${ANDROID_KEYSTORE_PATH}" \
    --ks-pass "pass:${ANDROID_KEYSTORE_PASSWORD}" \
    --ks-key-alias "${ANDROID_KEY_ALIAS}" \
    --key-pass "pass:${ANDROID_KEY_PASSWORD}" \
    --out "${output_apk}" \
    "${input_apk}"

  apksigner verify --verbose "${output_apk}" >/dev/null
else
  echo "warning: signing env vars are not fully set; copying unsigned/gradle output as-is"
  cp "${input_apk}" "${output_apk}"
fi

sha256="$(shasum -a 256 "${output_apk}" | awk '{print $1}')"

echo "Built APK: ${output_apk}"
echo "Version: ${version_name} (${version_code})"
echo "SHA256: ${sha256}"
