#!/bin/sh
set -eu

umask 077

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"
KEY_ALIAS=${WNH_ANDROID_SIGNING_KEY_ALIAS:-who-need-help-upload}
KEY_IMAGE="gradle:9.6.1-jdk17@sha256:7364ce528f33bb6038672bcef990d524f1ad8fbc292935819c235db886d0fae7"
run_id="$$-$(openssl rand -hex 4)"
temporary_keystore="$SIGNING_DIR/.who-need-help-upload.$run_id.p12"
temporary_password="$SIGNING_DIR/.who-need-help-upload.$run_id.password"

cleanup() {
  if [ -e "$temporary_keystore" ]; then
    unlink "$temporary_keystore"
  fi
  if [ -e "$temporary_password" ]; then
    unlink "$temporary_password"
  fi
}
trap cleanup EXIT HUP INT TERM

case "$KEY_ALIAS" in
  ''|*[!A-Za-z0-9._-]*)
    echo "WNH_ANDROID_SIGNING_KEY_ALIAS must use only letters, digits, dot, underscore, and dash." >&2
    exit 1
    ;;
esac

if [ -L "$SIGNING_DIR" ]; then
  echo "Refusing to use a symlink as the Android signing directory: $SIGNING_DIR" >&2
  exit 1
fi

install -d -m 700 "$SIGNING_DIR"

if [ -e "$KEYSTORE" ] || [ -e "$PASSWORD_FILE" ]; then
  echo "Android upload signing material already exists; nothing was overwritten:" >&2
  echo "  $KEYSTORE" >&2
  echo "  $PASSWORD_FILE" >&2
  exit 1
fi

openssl rand -hex 32 >"$temporary_password"
chmod 600 "$temporary_password"

docker run --rm \
  --user "$(id -u):$(id -g)" \
  --mount "type=bind,src=$SIGNING_DIR,dst=/secure" \
  --entrypoint keytool \
  "$KEY_IMAGE" \
  -genkeypair \
  -keystore "/secure/$(basename "$temporary_keystore")" \
  -storetype PKCS12 \
  -storepass:file "/secure/$(basename "$temporary_password")" \
  -keypass:file "/secure/$(basename "$temporary_password")" \
  -alias "$KEY_ALIAS" \
  -keyalg RSA \
  -keysize 2048 \
  -validity 10000 \
  -dname "CN=Who Need Help upload key"

docker run --rm \
  --user "$(id -u):$(id -g)" \
  --mount "type=bind,src=$SIGNING_DIR,dst=/secure,readonly" \
  --entrypoint keytool \
  "$KEY_IMAGE" \
  -list \
  -keystore "/secure/$(basename "$temporary_keystore")" \
  -storetype PKCS12 \
  -storepass:file "/secure/$(basename "$temporary_password")" \
  -alias "$KEY_ALIAS" >/dev/null

chmod 600 "$temporary_keystore"
mv "$temporary_keystore" "$KEYSTORE"
mv "$temporary_password" "$PASSWORD_FILE"

echo "Generated a dedicated Android upload key without placing secrets in the repository."
echo "Private keystore: $KEYSTORE"
echo "Password file: $PASSWORD_FILE"
echo "Back up both files before the first Play Console upload."
