#!/bin/sh
set -eu

ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
ENV_FILE=${WNH_ENV_FILE:-"$ROOT/.env"}
config_home=${XDG_CONFIG_HOME:-"$HOME/.config"}
SIGNING_DIR=${WNH_ANDROID_SIGNING_DIR:-"$config_home/who_need_help/android-release"}
KEYSTORE="$SIGNING_DIR/who-need-help-upload.p12"
PASSWORD_FILE="$SIGNING_DIR/who-need-help-upload.password"
OUTPUT_DIR=${WNH_ANDROID_RELEASE_OUTPUT_DIR:-"$ROOT/android/dist-release"}

case "$ENV_FILE" in
  /*) ;;
  *) ENV_FILE="$ROOT/$ENV_FILE" ;;
esac

if [ ! -f "$ENV_FILE" ]; then
  echo "Missing Android release environment file: $ENV_FILE" >&2
  exit 1
fi

set -a
# shellcheck source=/dev/null
. "$ENV_FILE"
set +a

: "${WNH_BASE_URL:?Set WNH_BASE_URL in the selected environment file}"
: "${WNH_TRACKING_MIN_TIME_MS:?Set WNH_TRACKING_MIN_TIME_MS in the selected environment file}"
: "${WNH_TRACKING_HTTP_TIMEOUT_MS:?Set WNH_TRACKING_HTTP_TIMEOUT_MS in the selected environment file}"
: "${WNH_ANDROID_VERSION_CODE:?Set WNH_ANDROID_VERSION_CODE in the selected environment file}"
: "${WNH_ANDROID_VERSION_NAME:?Set WNH_ANDROID_VERSION_NAME in the selected environment file}"
: "${WNH_ANDROID_SIGNING_KEY_ALIAS:?Set WNH_ANDROID_SIGNING_KEY_ALIAS in the selected environment file}"

for secret_file in "$KEYSTORE" "$PASSWORD_FILE"; do
  if [ ! -f "$secret_file" ]; then
    echo "Missing Android release signing file: $secret_file" >&2
    echo "Run scripts/init-android-release-signing.sh once." >&2
    exit 1
  fi

  mode=$(stat -c '%a' "$secret_file")
  case "$mode" in
    400|600) ;;
    *)
      echo "Android release signing file must have mode 0400 or 0600: $secret_file" >&2
      exit 1
      ;;
  esac
done

case "$OUTPUT_DIR" in
  /*) ;;
  *) OUTPUT_DIR="$ROOT/$OUTPUT_DIR" ;;
esac

docker build \
  --secret "id=android_upload_keystore,src=$KEYSTORE" \
  --secret "id=android_upload_password,src=$PASSWORD_FILE" \
  --secret "id=android_upload_alias,env=WNH_ANDROID_SIGNING_KEY_ALIAS" \
  --build-arg "WNH_BASE_URL=$WNH_BASE_URL" \
  --build-arg "WNH_TRACKING_MIN_TIME_MS=$WNH_TRACKING_MIN_TIME_MS" \
  --build-arg "WNH_TRACKING_HTTP_TIMEOUT_MS=$WNH_TRACKING_HTTP_TIMEOUT_MS" \
  --build-arg "WNH_ANDROID_VERSION_CODE=$WNH_ANDROID_VERSION_CODE" \
  --build-arg "WNH_ANDROID_VERSION_NAME=$WNH_ANDROID_VERSION_NAME" \
  --target release-artifact \
  --output "type=local,dest=$OUTPUT_DIR" \
  "$ROOT/android"

for artifact in \
  "$OUTPUT_DIR/who-need-help-release.apk" \
  "$OUTPUT_DIR/who-need-help-release.aab" \
  "$OUTPUT_DIR/signing-certificate.txt" \
  "$OUTPUT_DIR/bundle-signing-verification.txt" \
  "$OUTPUT_DIR/bundletool-validation.txt" \
  "$OUTPUT_DIR/lint-results-release.html"; do
  if [ ! -s "$artifact" ]; then
    echo "Android release build did not export the expected artifact: $artifact" >&2
    exit 1
  fi
done

sha256sum \
  "$OUTPUT_DIR/who-need-help-release.apk" \
  "$OUTPUT_DIR/who-need-help-release.aab"
echo "Signed Android APK, Play AAB, certificate report, and lint report: $OUTPUT_DIR"
