#!/usr/bin/env bash
# Build and upload the EasyLink Automations Pro release zip.
set -euo pipefail

PLUGIN_SLUG="easylink-automations-pro"
PRODUCT_SLUG="${EASYLINK_RELEASE_PRODUCT_SLUG:-$PLUGIN_SLUG}"
DEFAULT_API_BASE_URL="https://panel.easylinkautomations.io"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ZIP_PATH="${EASYLINK_RELEASE_ZIP_PATH:-${SCRIPT_DIR}/build/${PLUGIN_SLUG}.zip}"

usage() {
  cat <<'USAGE'
Usage:
  ./upload-pro-release.sh [version] [released_at]

Arguments:
  version      Optional. Defaults to the Version header in pro/easylink-automations-pro.php.
  released_at Optional. Defaults to the current local time in "YYYY-MM-DD HH:MM:SS" format.

Environment:
  EASYLINK_RELEASE_API_BASE_URL  Base URL. Defaults to https://panel.easylinkautomations.io
  EASYLINK_RELEASE_UPLOAD_URL    Full upload URL. Overrides EASYLINK_RELEASE_API_BASE_URL.
  EASYLINK_RELEASE_ADMIN_TOKEN   Bearer token for the upload API. Prompts when omitted.
  EASYLINK_RELEASE_PRODUCT_SLUG  Product slug. Defaults to easylink-automations-pro.
  EASYLINK_RELEASE_ZIP_PATH      Zip to upload. Defaults to build/easylink-automations-pro.zip.
  EASYLINK_RELEASE_SKIP_BUILD    Set to 1 to upload the existing zip without rebuilding.

Examples:
  ./upload-pro-release.sh 1.2.3 "2026-06-08 10:00:00"
  EASYLINK_RELEASE_UPLOAD_URL="https://panel.easylinkautomations.io/api/v1/products/easylink-automations-pro/versions/upload" ./upload-pro-release.sh
USAGE
}

error() {
  echo "Error: $*" >&2
  exit 1
}

require_command() {
  command -v "$1" >/dev/null 2>&1 || error "Required command not found: $1"
}

read_pro_version() {
  awk -F':' '/^[[:space:]]*\* Version:/ {
    gsub(/^[[:space:]]+|[[:space:]]+$/, "", $2)
    print $2
    exit
  }' "${SCRIPT_DIR}/pro/easylink-automations-pro.php"
}

build_upload_url() {
  if [[ -n "${EASYLINK_RELEASE_UPLOAD_URL:-}" ]]; then
    printf '%s\n' "$EASYLINK_RELEASE_UPLOAD_URL"
    return
  fi

  local base_url="${EASYLINK_RELEASE_API_BASE_URL:-$DEFAULT_API_BASE_URL}"
  base_url="${base_url%/}"
  printf '%s/api/v1/products/%s/versions/upload\n' "$base_url" "$PRODUCT_SLUG"
}

prompt_admin_token() {
  if [[ -n "${EASYLINK_RELEASE_ADMIN_TOKEN:-}" ]]; then
    return
  fi

  read -r -s -p "Admin token: " EASYLINK_RELEASE_ADMIN_TOKEN
  echo ""
  export EASYLINK_RELEASE_ADMIN_TOKEN
}

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  usage
  exit 0
fi

VERSION="${1:-${EASYLINK_RELEASE_VERSION:-$(read_pro_version)}}"
RELEASED_AT="${2:-${EASYLINK_RELEASED_AT:-$(date '+%Y-%m-%d %H:%M:%S')}}"
UPLOAD_URL="$(build_upload_url)"

[[ -n "$VERSION" ]] || error "Could not determine release version."
prompt_admin_token
[[ -n "${EASYLINK_RELEASE_ADMIN_TOKEN:-}" ]] || error "Admin token is required."

require_command curl

if [[ "${EASYLINK_RELEASE_SKIP_BUILD:-0}" != "1" ]]; then
  require_command composer
  require_command pnpm
  require_command rsync
  require_command zip

  echo "Building release zips..."
  "${SCRIPT_DIR}/build-zip.sh"
fi

[[ -f "$ZIP_PATH" ]] || error "Zip file not found: $ZIP_PATH"

echo "Uploading ${ZIP_PATH}"
echo "Version: ${VERSION}"
echo "Released at: ${RELEASED_AT}"
echo "Endpoint: ${UPLOAD_URL}"

curl -fsS -X POST "$UPLOAD_URL" \
  -H "Authorization: Bearer ${EASYLINK_RELEASE_ADMIN_TOKEN}" \
  -F "version=${VERSION}" \
  -F "released_at=${RELEASED_AT}" \
  -F "file=@${ZIP_PATH}"

echo ""
echo "Upload complete."
