#!/bin/bash

# Fix Atlantis Watchtower port conflict
echo "🔧 Fixing Atlantis port conflict by using port 8081 instead of 8080..."

API_KEY=REDACTED_API_KEY
BASE_URL="http://vishinator.synology.me:10000"

# Remove the current container
curl -s -X DELETE -H "X-API-Key: $API_KEY" \
  "$BASE_URL/api/endpoints/2/docker/containers/7bbb8db75728?force=true"

sleep 2

# Create new container with port 8081
create_response=$(curl -s -X POST -H "X-API-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  "$BASE_URL/api/endpoints/2/docker/containers/create?name=watchtower" \
  -d '{
    "Image": "containrrr/watchtower:latest",
    "Env": [
      "WATCHTOWER_CLEANUP=true",
      "WATCHTOWER_INCLUDE_RESTARTING=true",
      "WATCHTOWER_INCLUDE_STOPPED=true",
      "WATCHTOWER_REVIVE_STOPPED=false",
      "WATCHTOWER_POLL_INTERVAL=3600",
      "WATCHTOWER_TIMEOUT=10s",
      "WATCHTOWER_HTTP_API_UPDATE=true",
      "WATCHTOWER_HTTP_API_TOKEN="REDACTED_HTTP_TOKEN",
      "WATCHTOWER_NOTIFICATIONS=shoutrrr",
      "WATCHTOWER_NOTIFICATION_URL=generic+http://localhost:8082/updates",
      "TZ=America/Los_Angeles"
    ],
    "HostConfig": {
      "Binds": ["/var/run/docker.sock:/var/run/docker.sock"],
      "RestartPolicy": {"Name": "always"},
      "PortBindings": {"8080/tcp": [{"HostPort": "8081"}]}
    }
  }')

container_id=$(echo "$create_response" | jq -r '.Id')
echo "✅ Created container: ${container_id:0:12}"

# Start the container
curl -s -X POST -H "X-API-Key: $API_KEY" \
  "$BASE_URL/api/endpoints/2/docker/containers/$container_id/start"

echo "🚀 Started Atlantis Watchtower on port 8081"
