#!/bin/bash
# 🚀 Auto-generated by The AltStack
# https://thealtstack.com

echo "🔵 Starting AltStack Deployment..."

# 1. Check/Install Docker
if ! command -v docker &> /dev/null; then
    echo "📦 Docker not found. Installing..."
    curl -fsSL https://get.docker.com -o get-docker.sh
    sh get-docker.sh
    rm get-docker.sh
    echo "✅ Docker installed."
else
    echo "✅ Docker is already installed."
fi

# 2. Setup Directory
APP_DIR="authentik-deploy"
mkdir -p $APP_DIR
cd $APP_DIR
echo "📂 Created directory: $APP_DIR"

# 3. Create docker-compose.yml
echo "📄 Writing configuration..."
cat << 'INNER_EOF' > docker-compose.yml

# -------------------------------------------------------------------------
# 🚀 Created and distributed by The AltStack
# 🌍 https://thealtstack.com
# -------------------------------------------------------------------------

version: '3.8'

services:
  server:
    image: ghcr.io/goauthentik/server:latest
    container_name: authentik-server
    restart: unless-stopped
    command: server
    depends_on:
      - db
      - redis
    ports:
      - "9000:9000"
      - "9443:9443"
    environment:
      - AUTHENTIK_REDIS__HOST=redis
      - AUTHENTIK_POSTGRESQL__HOST=db
      - AUTHENTIK_POSTGRESQL__USER=authentik
      - AUTHENTIK_POSTGRESQL__NAME=authentik
      - AUTHENTIK_POSTGRESQL__PASSWORD=authentik
      - AUTHENTIK_SECRET_KEY=generate-a-random-secret-key

  worker:
    image: ghcr.io/goauthentik/server:latest
    container_name: authentik-worker
    restart: unless-stopped
    command: worker
    depends_on:
      - db
      - redis
    environment:
      - AUTHENTIK_REDIS__HOST=redis
      - AUTHENTIK_POSTGRESQL__HOST=db
      - AUTHENTIK_POSTGRESQL__USER=authentik
      - AUTHENTIK_POSTGRESQL__NAME=authentik
      - AUTHENTIK_POSTGRESQL__PASSWORD=authentik
      - AUTHENTIK_SECRET_KEY=generate-a-random-secret-key

  db:
    image: postgres:12-alpine
    container_name: authentik-db
    restart: unless-stopped
    environment:
      - POSTGRES_PASSWORD=authentik
      - POSTGRES_USER=authentik
      - POSTGRES_DB=authentik
    volumes:
      - authentik_db_data:/var/lib/postgresql/data

  redis:
    image: redis:6-alpine
    container_name: authentik-redis
    restart: unless-stopped

volumes:
  authentik_db_data:

INNER_EOF

# 4. Start Services
echo "🚀 Starting services..."
docker compose up -d

echo ""
echo "✅ Deployment Complete!"
echo "👉 Your authentik stack is running."
