#!/usr/bin/env bash
# Sync .env files from the self-hosted runner filesystem into the repo.
# Jenkins variant — exports variables as KEY=VALUE lines into $CI_ENV_FILE,
# which the Jenkinsfile loads with readProperties + withEnv. Jenkins has no
# equivalent of GitHub Actions' $GITHUB_ENV, and each `sh` step runs in its
# own process, so this file is the hand-off point between stages.
#
# Usage:
#   PROJECT=edr-freight BRANCH=main CI_ENV_FILE=/tmp/passenger-api.env \
#     ./scripts/deploy/sync-env-from-server-jenkins.sh passenger-api
#
# Server layout (one file per service):
#   /home/user/environmen/<project>/<branch-slug>/freight-api.env
#   /home/user/environmen/<project>/<branch-slug>/freight-portal.env
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}}"
CI_ENV_FILE="${CI_ENV_FILE:?CI_ENV_FILE is required (e.g. \${WORKSPACE}/.ci-env/<service>.env)}"
if [[ ! -d "${ENV_ROOT}" ]]; then
  echo "Environment directory not found: ${ENV_ROOT}" >&2
  exit 1
fi
echo "Using environment directory: ${ENV_ROOT}"
mkdir -p "$(dirname "${CI_ENV_FILE}")"
if [[ -d "${CI_ENV_FILE}" ]]; then
  echo "Removing stale directory at ${CI_ENV_FILE}" >&2
  rm -rf "${CI_ENV_FILE}"
fi
: > "${CI_ENV_FILE}"
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
  service_var=$(echo "${service}" | tr '[:lower:]-' '[:upper:]_')
  echo "${service_var}_PORT=${port_value}" >> "${CI_ENV_FILE}"
  echo "Exported ${service_var}_PORT from ${src}"
  # Forward NEXT_PUBLIC_* and VITE_* vars so docker compose build can inject them as build args.
  grep -E '^[[:space:]]*(NEXT_PUBLIC_|VITE_)[A-Za-z0-9_]+=' "${src}" \
    | sed -E 's/^[[:space:]]*//' >> "${CI_ENV_FILE}" || true
done
