#!/bin/bash

# ==========================================
# 1. Define Variables & Paths
# ==========================================
BASE_DIR="/home/user/containerdata"
WEB_ROOT="$BASE_DIR/0"
FB_DB_DIR="$BASE_DIR/fb_database"
FB_CONF_DIR="$BASE_DIR/fb_config"
CADDY_ETC_DIR="$BASE_DIR/caddy/etc"
SYNCTHING_CONF_DIR="$BASE_DIR/syncthing_config"

# ==========================================
# 2. Install Docker (Debian/Ubuntu) if missing
# ==========================================
if ! command -v docker &> /dev/null; then
    echo "Docker not found. Installing Docker..."
    apt-get update
    apt-get install -y ca-certificates curl gnupg
    install -m 0755 -d /etc/apt/keyrings
    curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
    chmod a+r /etc/apt/keyrings/docker.gpg
    echo "deb [arch="$(dpkg --print-architecture)" signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/debian "$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
    apt-get update
    apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
else
    echo "Docker is already installed. Skipping installation."
fi

# ==========================================
# 3. Create Directory Structure
# ==========================================
echo "Ensuring directory structure exists..."
mkdir -p "$WEB_ROOT"
mkdir -p "$FB_DB_DIR"
mkdir -p "$FB_CONF_DIR"
mkdir -p "$CADDY_ETC_DIR"
mkdir -p "$SYNCTHING_CONF_DIR"

if [ ! -f "$FB_DB_DIR/filebrowser.db" ]; then
    echo "Initializing empty Filebrowser database..."
    touch "$FB_DB_DIR/filebrowser.db"
else
    echo "Filebrowser database already exists. Preserving data."
fi

# ==========================================
# 4. Generate Caddyfile (Conditionally)
# ==========================================
if [ ! -f "$CADDY_ETC_DIR/Caddyfile" ]; then
    echo "Generating Caddyfile..."
    cat << 'EOF' > "$CADDY_ETC_DIR/Caddyfile"
:80 {
    root * /var/www/html
    encode gzip zstd

    # PHP support (shared backend)
    php_fastcgi 172.21.0.4:9000 {
        capture_stderr
    }

    # Serve static files + directory index
    file_server {
        index index.html index.php
        browse   # optional: show directory listing if no index
    }

    # Security headers
    header {
        X-Content-Type-Options nosniff
        X-Frame-Options DENY
        X-XSS-Protection "1; mode=block"
        Referrer-Policy strict-origin-when-cross-origin
        -Server
    }

    log {
        output stdout
        format console
    }
}
EOF
else
    echo "Caddyfile already exists at $CADDY_ETC_DIR/Caddyfile. Skipping to prevent overwrite."
fi

# ==========================================
# 5. Generate docker-compose.yml (Forced Overwrite)
# ==========================================
echo "Generating docker-compose.yml (Overwriting existing file to ensure state)..."
cat << EOF > "$BASE_DIR/docker-compose.yml"
services:
  php:
    container_name: php
    image: php:8.4-rc-fpm-trixie
    restart: unless-stopped
    networks:
      simpleSolution-nw:
        ipv4_address: 172.21.0.4
    volumes:
      - $WEB_ROOT:/var/www/html
    healthcheck:
      test: ["CMD", "php-fpm", "-t"]
      interval: 10s
      timeout: 5s
      retries: 3
      start_period: 10s

  filebrowser_0:
    container_name: filebrowser_0
    image: filebrowser/filebrowser:latest
    restart: unless-stopped
    user: "33:33"
    ports:
      - "21401:80"
    networks:
      simpleSolution-nw:
        ipv4_address: 172.21.0.2
    volumes:
      - $WEB_ROOT:/srv
      - $FB_DB_DIR/filebrowser.db:/database/filebrowser.db
      - $FB_CONF_DIR:/config
    environment:
      - FB_DATABASE=/database/filebrowser.db

  syncthing:
    container_name: syncthing
    image: syncthing/syncthing:latest
    restart: unless-stopped
    user: "33:33"
    environment:
      - STGUIADDRESS=0.0.0.0:8384
    networks:
      simpleSolution-nw:
        ipv4_address: 172.21.0.5
    ports:
      - "21403:8384"
      - "22000:22000/tcp"
      - "22000:22000/udp"
      - "21027:21027/udp"
    volumes:
      - $WEB_ROOT:/var/syncthing/Sync
      - $SYNCTHING_CONF_DIR:/var/syncthing/config

  caddy_0:
    container_name: caddy_0
    image: caddy:latest
    restart: unless-stopped
    depends_on:
      php:
        condition: service_healthy
    ports:
      - "21402:80"
    networks:
      simpleSolution-nw:
        ipv4_address: 172.21.0.3
    volumes:
      - $CADDY_ETC_DIR/Caddyfile:/etc/caddy/Caddyfile:ro
      - $WEB_ROOT:/var/www/html:ro
    command: caddy run --config /etc/caddy/Caddyfile --adapter caddyfile

networks:
  simpleSolution-nw:
    name: simpleSolution-nw
    driver: bridge
    ipam:
      config:
        - subnet: 172.21.0.0/24
EOF

# ==========================================
# 6. Apply Unified Permissions
# ==========================================
echo "Applying unified permissions (UID 33:33) to $BASE_DIR..."
chown -R 33:33 "$BASE_DIR"
find "$BASE_DIR" -type d -exec chmod 755 {} \;
find "$BASE_DIR" -type f -exec chmod 644 {} \;

# ==========================================
# 7. Start the Docker Compose Stack
# ==========================================
echo "Starting or updating Docker Compose stack..."
cd "$BASE_DIR" || exit
docker compose up -d --remove-orphans

echo "=========================================="
echo "Deployment Complete!"
echo "Web Root: $WEB_ROOT"
echo "Filebrowser Port: 21401"
echo "Caddy Port: 21402"
echo "Syncthing GUI Port: 21403"
echo "Permissions applied: UID/GID 33 (www-data) with 755/644."
echo "=========================================="
