#!/usr/bin/env bash

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PUBSPEC_FILE="$ROOT_DIR/pubspec.yaml"
OUTPUT_DIR="$ROOT_DIR/dist/android"
SOURCE_APK="$ROOT_DIR/build/app/outputs/flutter-apk/app-release.apk"
APP_SLUG="jamshalat-masjid-screen"
KEY_PROPERTIES_FILE="$ROOT_DIR/android/key.properties"

if [[ ! -f "$PUBSPEC_FILE" ]]; then
  echo "pubspec.yaml not found at: $PUBSPEC_FILE" >&2
  exit 1
fi

if [[ ! -f "$KEY_PROPERTIES_FILE" ]]; then
  echo "Missing production signing config: $KEY_PROPERTIES_FILE" >&2
  echo "Copy android/key.properties.example to android/key.properties and fill in your real keystore values." >&2
  exit 1
fi

VERSION_LINE="$(grep -E '^version:' "$PUBSPEC_FILE" | head -n 1 | sed -E 's/^version:[[:space:]]*//')"
if [[ -z "$VERSION_LINE" ]]; then
  echo "Unable to read version from pubspec.yaml" >&2
  exit 1
fi

VERSION_NAME="${VERSION_LINE%%+*}"
if [[ "$VERSION_LINE" == *"+"* ]]; then
  BUILD_NUMBER="${VERSION_LINE##*+}"
else
  BUILD_NUMBER="0"
fi

VERSIONED_APK="$OUTPUT_DIR/${APP_SLUG}-v${VERSION_NAME}-build${BUILD_NUMBER}.apk"
LATEST_APK="$OUTPUT_DIR/${APP_SLUG}-latest.apk"
CHECKSUM_FILE="$VERSIONED_APK.sha256"
JSON_TEMPLATE_FILE="$OUTPUT_DIR/latest.json.example"
PUBLISHED_AT="$(date '+%Y-%m-%dT%H:%M:%S%z')"

mkdir -p "$OUTPUT_DIR"

echo "Building Android release APK for version $VERSION_NAME+$BUILD_NUMBER"
(cd "$ROOT_DIR" && flutter build apk --release "$@")

if [[ ! -f "$SOURCE_APK" ]]; then
  echo "Expected APK not found: $SOURCE_APK" >&2
  exit 1
fi

cp "$SOURCE_APK" "$VERSIONED_APK"
cp "$SOURCE_APK" "$LATEST_APK"

APK_SHA256="$(shasum -a 256 "$VERSIONED_APK" | awk '{print $1}')"
printf '%s  %s\n' "$APK_SHA256" "$(basename "$VERSIONED_APK")" > "$CHECKSUM_FILE"

cat > "$JSON_TEMPLATE_FILE" <<EOF
{
  "latest_version": "$VERSION_NAME",
  "version_code": $BUILD_NUMBER,
  "apk_url": "UPLOAD_APK_URL_HERE",
  "published_at": "$PUBLISHED_AT",
  "notes": "FILL_RELEASE_NOTES_HERE",
  "sha256": "$APK_SHA256",
  "min_supported_version_code": 1
}
EOF

echo
echo "Build complete."
echo "Versioned APK : $VERSIONED_APK"
echo "Latest APK    : $LATEST_APK"
echo "SHA-256 file  : $CHECKSUM_FILE"
echo "JSON template : $JSON_TEMPLATE_FILE"
echo
echo "Release signing config was loaded from android/key.properties."
