#!/bin/bash
set -e
set -o pipefail

GLOBAL_ENV_FILE="/medicine-config/.env"
ENV_FILE="/medicine-config/medicine/.env"

HTTP_PORT="$1"
HTTPS_PORT="$2"

set_env_var () {
  local key="$1"
  local value="$2"

  if grep -qE "^${key}=" "$ENV_FILE"; then
    sed -i "s|^${key}=.*|${key}=${value}|" "$ENV_FILE"
  else
    echo "${key}=${value}" >> "$ENV_FILE"
  fi
}

unset_env_var () {
  local key="$1"

  if grep -qE "^${key}=" "$ENV_FILE"; then
    sed -i "/^${key}=/d" "$ENV_FILE"
  fi
}

echo "HTTP порт: $HTTP_PORT"
echo "HTTPS порт: $HTTPS_PORT"
echo ""

touch "$ENV_FILE"
touch "$GLOBAL_ENV_FILE"

if [ -n "$HTTP_PORT" ] && [ "$HTTP_PORT" != "80" ]; then
  set_env_var "NGINX_HTTP_PORT" "$HTTP_PORT"
else
  unset_env_var "NGINX_HTTP_PORT"
fi

if [ -n "$HTTPS_PORT" ] && [ "$HTTPS_PORT" != "443" ]; then
  set_env_var "NGINX_HTTPS_PORT" "$HTTPS_PORT"
else
  unset_env_var "NGINX_HTTPS_PORT"
fi

(cd /medicine-config/medicine && docker compose stop && docker compose up -d)

echo "✅ Настройки изменены"
