#!/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///freight-api.env # /home/user/environmen///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}}" 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" ["gps-tracker"]="apps/edr-gps-tracker/.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" ["synapse"]="infrastructure/matrix/synapse/.env" # element-web has no runtime secrets (its config.json is baked into the # image), but the sync step still runs unconditionally per service and # needs a PORT= line to compute ELEMENT_WEB_PORT for docker compose. ["element-web"]="infrastructure/matrix/element/.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_* 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:]]*//' >> "${GITHUB_ENV}" || true fi done