#!/usr/bin/env bash
# Sync .env files from the self-hosted runner filesystem into the repo.
#
# Usage:
#   PROJECT=edr-freight BRANCH=main ./scripts/deploy/sync-env-from-server.sh freight-api freight-portal freight-backoffice
#
# Server layout (one file per service):
#   /home/user/environmen/<project>/<branch-slug>/freight-api.env
#   /home/user/environmen/<project>/<branch-slug>/freight-portal.env
#   /home/user/environmen/<project>/<branch-slug>/freight-web.build.env  (optional, exports VITE_API_URL etc.)

set -euo pipefail

DEPLOY_USER="${DEPLOY_USER:-tria}"
BRANCH="${BRANCH:?BRANCH is required}"
BRANCH_SLUG="${BRANCH_SLUG:-$(echo "${BRANCH}" | tr "[:upper:]" "[:lower:]" | sed -E "s/[^a-z0-9]+/-/g; s/^-+//; s/-+$//")}"
ENV_ROOT="${ENV_ROOT:-/home/${DEPLOY_USER}/environment/edr/${BRANCH_SLUG}/${PROJECT:?PROJECT is required}}"

if [[ ! -d "${ENV_ROOT}" ]]; then
  echo "Environment directory not found: ${ENV_ROOT}" >&2
  exit 1
fi

echo "Using environment directory: ${ENV_ROOT}"

declare -A SERVICE_ENV_TARGET=(
  ["freight-api"]="apps/edr-freight-api/.env"
  ["freight-portal"]="apps/edr-freight-web/portal/.env"
  ["freight-backoffice"]="apps/edr-freight-web/backoffice/.env"
  ["passenger-api"]="apps/edr-passenger-api/.env"
  ["passenger-portal"]="apps/edr-passenger-web/portal/.env"
  ["passenger-backoffice"]="apps/edr-passenger-web/backoffice/.env"
  ["payment-api"]="apps/edr-payment-api/.env"
)

for service in "$@"; do
  src="${ENV_ROOT}/${service}.env"
  dest="${SERVICE_ENV_TARGET[${service}]:-}"

  if [[ -z "${dest}" ]]; then
    echo "Unknown service: ${service}" >&2
    exit 1
  fi

  if [[ ! -f "${src}" ]]; then
    echo "Missing env file: ${src}" >&2
    exit 1
  fi

  mkdir -p "$(dirname "${dest}")"
  cp "${src}" "${dest}"
  echo "Synced ${src} -> ${dest}"

  port_value=$(sed -n -E 's/^[[:space:]]*PORT[[:space:]]*=[[:space:]]*"?([^"#]+)"?[[:space:]]*(#.*)?$/\1/p' "${src}" | head -n1 | tr -d '[:space:]')
  if [[ -z "${port_value}" ]]; then
    echo "Missing required PORT in env file: ${src}" >&2
    exit 1
  fi

  if [[ -n "${GITHUB_ENV:-}" ]]; then
    service_var=$(echo "${service}" | tr '[:lower:]-' '[:upper:]_')
    echo "${service_var}_PORT=${port_value}" >> "${GITHUB_ENV}"
    echo "Exported ${service_var}_PORT from ${src}"

    # Forward NEXT_PUBLIC_* vars so docker compose build can inject them as build args.
    grep -E '^[[:space:]]*NEXT_PUBLIC_[A-Za-z0-9_]+=' "${src}" \
      | sed -E 's/^[[:space:]]*//' >> "${GITHUB_ENV}" || true
  fi
done

# Optional build-time variables (VITE_API_URL, etc.)
# Set BUILD_ENV_FILE=freight-web.build.env or passenger-web.build.env per workflow.
build_env_file="${BUILD_ENV_FILE:-web.build.env}"
build_env="${ENV_ROOT}/${build_env_file}"
if [[ -f "${build_env}" ]]; then
  echo "Loading build variables from ${build_env}"
  set -a
  # shellcheck disable=SC1090
  source "${build_env}"
  set +a

  if [[ -n "${GITHUB_ENV:-}" ]]; then
    grep -E '^[[:space:]]*export[[:space:]]+[A-Za-z_][A-Za-z0-9_]*=' "${build_env}" \
      | sed -E 's/^[[:space:]]*export[[:space:]]+//' >> "${GITHUB_ENV}"
    echo "Wrote build variables to GITHUB_ENV"
  fi
fi
