#!/bin/bash
set -e
CONTAINER_NAME="dashcaddy-api"
IMAGE="dashcaddy-dashcaddy-api:latest"
DATA_DIR="/opt/dashcaddy/dashcaddy-api/data"
CADDYFILE="/etc/caddy/Caddyfile"
ASSETS_DIR="/var/www/dashcaddy-status/assets"
UPDATES_DIR="/opt/dashcaddy/updates"
BACKUPS_DIR="/opt/dashcaddy/backups"
HOST_IP="172.17.0.1"
# Local Technitium (binds 0.0.0.0:53) resolves *.sami + recurses for docker subnet
# external fallback. Without this the container only has 8.8.8.8 and every
# *.sami health-check probe fails with ENOTFOUND (uptime bars stay empty).
DNS_PRIMARY="100.121.150.22"   # Technitium (Tailscale IP) — resolves *.sami
DNS_FALLBACK="8.8.8.8"

# Always recreate to ensure env vars are correct (CONFIG_FILE defaults to /etc/dashcaddy/ which doesn't exist)
if docker ps -a --format "{{.Names}}" | grep -q "^${CONTAINER_NAME}$"; then
  echo "[start.sh] Recreating container to apply correct env vars..."
  docker rm -f ${CONTAINER_NAME}
fi

echo "[start.sh] Creating container with full config..."
docker run -d --restart unless-stopped --name ${CONTAINER_NAME} \
  --dns ${DNS_PRIMARY} \
  --dns ${DNS_FALLBACK} \
  -p 127.0.0.1:3001:3001 \
  -v ${DATA_DIR}:/app/data \
  -v ${BACKUPS_DIR}:/app/backups \
  -v ${CADDYFILE}:/caddyfile \
  -v /var/run/docker.sock:/var/run/docker.sock \
  -v ${ASSETS_DIR}:/app/assets \
  -v ${UPDATES_DIR}:/app/updates \
  -v /opt/sami-files/logs:/opt/sami-files/logs:ro \
  -e NODE_ENV=production \
  -e SERVICES_FILE=/app/data/services.json \
  -e CONFIG_FILE=/app/data/config.json \
  -e BACKUP_DIR=/app/backups \
  -e DNS_CREDENTIALS_FILE=/app/data/dns-credentials.json \
  -e CREDENTIALS_FILE=/app/data/credentials.json \
  -e ENCRYPTION_KEY_FILE=/app/data/.encryption-key \
  -e HEALTH_HISTORY_FILE=/app/data/health-history.json \
  -e HEALTH_CONFIG_FILE=/app/data/health-config.json \
  -e CADDYFILE_PATH=/caddyfile \
  -e CADDY_ADMIN_URL=http://${HOST_IP}:2019 \
  -e ASSETS_DIR=/app/assets \
  -e DASHCADDY_API_SOURCE_DIR=/opt/dashcaddy/dashcaddy-api \
  ${IMAGE}
