#!/usr/bin/env bash

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
KEYSTORE_PROPERTIES="$SCRIPT_DIR/keystore.properties"

log() {
  printf '\n[%s] %s\n' "create-upload-key" "$1"
}

fail() {
  echo "$1" >&2
  exit 1
}

require_tool() {
  if ! command -v "$1" >/dev/null 2>&1; then
    fail "Missing required tool: $1"
  fi
}

get_property() {
  local key="$1"
  python - "$KEYSTORE_PROPERTIES" "$key" <<'PY'
from pathlib import Path
import sys

path = Path(sys.argv[1])
target_key = sys.argv[2]

for raw_line in path.read_text().splitlines():
    line = raw_line.strip()
    if not line or line.startswith('#'):
        continue
    if '=' not in line:
        continue
    key, value = line.split('=', 1)
    if key.strip() == target_key:
        print(value.strip())
        break
PY
}

ensure_required_property() {
  local key="$1"
  local value="$2"

  if [ -z "$value" ]; then
    fail "Missing required property '$key' in $KEYSTORE_PROPERTIES"
  fi
}

main() {
  require_tool keytool
  require_tool python

  if [ ! -f "$KEYSTORE_PROPERTIES" ]; then
    fail "Missing $KEYSTORE_PROPERTIES. Create it from keystore.properties.example first."
  fi

  local store_file
  local store_password
  local key_alias
  local key_password

  store_file="$(get_property storeFile)"
  store_password="$(get_property storePassword)"
  key_alias="$(get_property keyAlias)"
  key_password="$(get_property keyPassword)"

  ensure_required_property storeFile "$store_file"
  ensure_required_property storePassword "$store_password"
  ensure_required_property keyAlias "$key_alias"
  ensure_required_property keyPassword "$key_password"

  if [ -f "$store_file" ]; then
    fail "Keystore already exists at $store_file. Delete or move it first if you want to regenerate it."
  fi

  mkdir -p "$(dirname "$store_file")"

  log "Creating upload keystore at $store_file"
  keytool -genkeypair \
    -v \
    -keystore "$store_file" \
    -storepass "$store_password" \
    -alias "$key_alias" \
    -keypass "$key_password" \
    -keyalg RSA \
    -keysize 2048 \
    -validity 10000 \
    -dname "CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, S=Unknown, C=US"

  log "Upload keystore created successfully"
  log "Back up both the keystore file and the matching keystore.properties secrets"
}

main "$@"