#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Prefer .env next to install.sh, but allow .env in the parent folder (zip root)
ENV_FILE="$ROOT_DIR/.env"
PARENT_ENV="$ROOT_DIR/../.env"

API_BASE_DEFAULT="https://api.blogger.mytown.ink"

if [ ! -f "$ENV_FILE" ]; then
  if [ -f "$PARENT_ENV" ]; then
    cp -f "$PARENT_ENV" "$ENV_FILE"
  else
    echo "ERROR: .env not found."
    echo "Expected either:"
    echo "  - $ENV_FILE"
    echo "  - $PARENT_ENV"
    echo ""
    echo "Download the kit again from the Paid page."
    exit 1
  fi
fi

TENANT_REF="$(grep -E '^TENANT_REF=' "$ENV_FILE" | head -n1 | cut -d= -f2- | tr -d '\r' || true)"
LICENSE_KEY="$(grep -E '^LICENSE_KEY=' "$ENV_FILE" | head -n1 | cut -d= -f2- | tr -d '\r' || true)"

API_BASE="$(grep -E '^API_BASE_URL=' "$ENV_FILE" | head -n1 | cut -d= -f2- | tr -d '\r' || true)"
if [ -z "${API_BASE:-}" ]; then API_BASE="$API_BASE_DEFAULT"; fi

if [ -z "${TENANT_REF:-}" ] || [ -z "${LICENSE_KEY:-}" ]; then
  echo "ERROR: TENANT_REF or LICENSE_KEY missing in .env"
  exit 1
fi

if ! command -v curl >/dev/null 2>&1; then
  echo "ERROR: curl is required"
  exit 1
fi

echo "[Blogger Kit] TENANT_REF=$TENANT_REF"
echo "[Blogger Kit] API=$API_BASE"

PKG_OUT="$ROOT_DIR/blogger-app-package.tar.gz"
TMP_HEADERS="$(mktemp)"

HTTP_CODE="$(curl -sS -o "$PKG_OUT" -D "$TMP_HEADERS" -w "%{http_code}" \
  -X POST "$API_BASE/kit/package.php" \
  -H "Content-Type: application/json" \
  -d "{\"ref\":\"$TENANT_REF\",\"license\":\"$LICENSE_KEY\"}")"

if [ "$HTTP_CODE" != "200" ]; then
  echo "ERROR: Package download failed (HTTP $HTTP_CODE)"
  echo "---- Response headers ----"
  sed -n '1,80p' "$TMP_HEADERS" || true
  echo "---- Response body (first 20 lines) ----"
  sed -n '1,20p' "$PKG_OUT" || true
  rm -f "$TMP_HEADERS" "$PKG_OUT"
  exit 1
fi

rm -f "$TMP_HEADERS"

if ! tar -tzf "$PKG_OUT" >/dev/null 2>&1; then
  echo "ERROR: Downloaded package is not a valid tar.gz"
  file "$PKG_OUT" || true
  exit 1
fi

INSTALL_DIR="$ROOT_DIR/app"
mkdir -p "$INSTALL_DIR"

echo "[Blogger Kit] Extracting package to: $INSTALL_DIR"
tar -xzf "$PKG_OUT" -C "$INSTALL_DIR"

# Keep a copy of tenant env inside app for the installed app to use
cp -f "$ENV_FILE" "$INSTALL_DIR/.env" || true

echo ""
echo "Install complete."
echo "Installed to: $INSTALL_DIR"
echo ""
