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

DEPLOY_PATH="${DEPLOY_PATH:-/opt/vpn-proxy}"
GATEWAY_IMAGE="${GATEWAY_IMAGE:?GATEWAY_IMAGE is required}"
PULL_IMAGE="${PULL_IMAGE:-true}"

echo "Preparing deploy directory: ${DEPLOY_PATH}"
mkdir -p "${DEPLOY_PATH}"

cat > "${DEPLOY_PATH}/docker-compose.server.yml" <<EOF
services:
  vpn-proxy-gateway:
    image: ${GATEWAY_IMAGE}
    container_name: vpn-proxy-gateway
    network_mode: host
    cap_add:
      - NET_ADMIN
      - NET_RAW
    env_file:
      - .env
    environment:
      DATA_DIR: /var/lib/vpn-proxy
      SING_BOX_CACHE: /var/lib/sing-box/cache.db
    volumes:
      - vpn-proxy-data:/var/lib/vpn-proxy
      - sing-box-cache:/var/lib/sing-box
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-fsS", "http://127.0.0.1:\${PORT:-3456}/api/state"]
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 20s

volumes:
  vpn-proxy-data:
  sing-box-cache:
EOF

if [ ! -f "${DEPLOY_PATH}/.env" ]; then
  cat > "${DEPLOY_PATH}/.env" <<'EOF'
PORT=3456
PROXY_PORT=8080
PROXY_BIND_IP=0.0.0.0
TPROXY_PORT=7895
TPROXY_MARK=1
TPROXY_TABLE=100
TPROXY_CHAIN=VPN_PROXY_TPROXY
TPROXY_SOURCE_BYPASS_CHAIN=VPN_PROXY_SRC_BYPASS
TPROXY_SOURCE_FORWARD_CHAIN=VPN_PROXY_FWD_BYPASS
TPROXY_SOURCE_NAT_CHAIN=VPN_PROXY_NAT_BYPASS
TPROXY_BYPASS_SOURCE_CIDRS=
ROUTING_RU_DIRECT=true
LOG_LEVEL=info
EOF
  echo "Created default .env. Edit ${DEPLOY_PATH}/.env if this server needs different ports."
else
  echo "Preserving existing .env"
fi

cd "${DEPLOY_PATH}"

echo "Pulling image: ${GATEWAY_IMAGE}"
if [ "${PULL_IMAGE}" = "true" ]; then
  docker compose -f docker-compose.server.yml pull
else
  echo "Skipping image pull; using local image ${GATEWAY_IMAGE}"
fi

echo "Starting gateway..."
docker compose -f docker-compose.server.yml up -d

echo "Current container:"
docker ps --filter "name=vpn-proxy-gateway"
