#!/bin/bash
set -e

echo "⚙️  Setting up Slack to ntfy middleware..."

# Check if Docker is installed
if ! command -v docker &> /dev/null; then
    echo "❌ Docker is not installed. Please install Docker first."
    exit 1
fi

# Check if Docker Compose is available
if ! docker compose version &> /dev/null; then
    echo "❌ Docker Compose is not available. Please install Docker Compose."
    exit 1
fi

echo "✅ Docker and Docker Compose are available"

# Prompt for configuration
echo
echo "📝 Please provide your ntfy server configuration:"
read -p "ntfy server URL (e.g., https://ntfy.example.com): " NTFY_URL
read -p "Bearer token (e.g., tk_xxxxx) [optional]: " NTFY_TOKEN
read -p "ntfy username (for basic auth) [optional]: " NTFY_USERNAME
read -p "ntfy password (for basic auth) [optional]: " NTFY_PASSWORD

# Update docker-compose.yml
if [ ! -z "$NTFY_URL" ]; then
    sed -i '' "s|https://your-ntfy-server.com|$NTFY_URL|g" docker-compose.yml
fi

# Reset all auth lines to commented placeholders first to ensure a clean state
sed -i '' "s|^      - NTFY_TOKEN=.*|      # - NTFY_TOKEN=tk_your_bearer_token_here|" docker-compose.yml
sed -i '' "s|^      - NTFY_USERNAME=.*|      # - NTFY_USERNAME=your_username|" docker-compose.yml
sed -i '' "s|^      - NTFY_PASSWORD=.*|      # - NTFY_PASSWORD=your_password|" docker-compose.yml

if [ ! -z "$NTFY_TOKEN" ]; then
    sed -i '' "s|^      # - NTFY_TOKEN=tk_your_bearer_token_here|      - NTFY_TOKEN=$NTFY_TOKEN|" docker-compose.yml
elif [ ! -z "$NTFY_USERNAME" ] && [ ! -z "$NTFY_PASSWORD" ]; then
    sed -i '' "s|^      # - NTFY_USERNAME=your_username|      - NTFY_USERNAME=$NTFY_USERNAME|" docker-compose.yml
    sed -i '' "s|^      # - NTFY_PASSWORD=your_password|      - NTFY_PASSWORD=$NTFY_PASSWORD|" docker-compose.yml
fi

echo "✅ Configuration updated in docker-compose.yml"

# Build and start
echo "🐳 Building and starting the service..."
docker compose up -d --build

echo "✅ Service is starting up..."
echo
echo "Next steps:"
echo "1. Test the service: ./scripts/test.sh"
echo "2. Check logs: docker compose logs -f"
echo "3. Configure Slack webhook URL: http://your-server-ip:8080/your-topic-name"
