#!/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="coder-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:
  coder:
    image: ghcr.io/coder/coder:latest
    container_name: coder
    restart: unless-stopped
    depends_on:
      - db
    ports:
      - "7080:7080"
    environment:
      - CODER_PG_CONNECTION_URL=postgresql://coder:coder@db:5432/coder
      - CODER_ACCESS_URL=http://localhost:7080
      - CODER_HTTP_ADDRESS=0.0.0.0:7080
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock

  db:
    image: postgres:13
    container_name: coder-db
    restart: unless-stopped
    environment:
      - POSTGRES_USER=coder
      - POSTGRES_PASSWORD=coder
      - POSTGRES_DB=coder
    volumes:
      - coder_db_data:/var/lib/postgresql/data

volumes:
  coder_db_data:

INNER_EOF

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

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