#!/usr/bin/env bash
set -euo pipefail


step() {
  echo
  echo "=================================================="
  echo "  👉 $1"
  echo "=================================================="
}


require_root() {
  if [ "$(id -u)" -ne 0 ]; then
    echo "Este script debe ejecutarse como root (o con sudo)."
    exit 1
  fi
}

require_root

step "Instalando Docker, docker compose plugin y certbot"

apt-get update -y
	
# Dependencias para repositorio Docker
apt-get install -y \
  ca-certificates \
  curl \
  gnupg \
  lsb-release

# Clave GPG de Docker
if [ ! -f /etc/apt/keyrings/docker.gpg ]; then
  install -m 0755 -d /etc/apt/keyrings
  curl -fsSL https://download.docker.com/linux/ubuntu/gpg | \
    gpg --dearmor -o /etc/apt/keyrings/docker.gpg
fi

# Repo Docker estable
if [ ! -f /etc/apt/sources.list.d/docker.list ]; then
  echo \
    "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
    $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
    tee /etc/apt/sources.list.d/docker.list > /dev/null
fi

apt-get update -y

apt-get install -y \
  docker-ce \
  docker-ce-cli \
  containerd.io \
  docker-buildx-plugin \
  docker-compose-plugin \
  git 
	
systemctl enable docker
systemctl start docker
	
# Abrimos puertos en ufw si está activo
if command -v ufw >/dev/null 2>&1; then
  if ufw status | grep -q "Status: active"; then
    step "Configurando firewall (ufw) para permitir 80 y 443"
    ufw allow 80/tcp || true
    ufw allow 443/tcp || true
  fi
fi

# Creamos carpeta del proxy con docker compose. 

mkdir -p /opt/beyondcx/traefik

cat > /opt/beyondcx/traefik/docker-compose.yaml <<EOF
services:
    traefik:
        image: traefik:v3.6.1
        container_name: traefik-prod-1
        ports:
            - "80:80"
            - "443:443"
            - "8080:8080"
        environment:
            - DO_AUTH_TOKEN=\${DO_AUTH_TOKEN}
        volumes:
            - /var/run/docker.sock:/var/run/docker.sock
            - ./config/traefik.yml:/etc/traefik/traefik.yaml:ro
            - ./data/certs:/var/traefik/certs/:rw
            - ./config/conf:/etc/traefik/conf/:rw
            - ./logs:/var/traefik/logs:rw
        logging:
          driver: "json-file"
          options:
            max-size: "100m"
        networks:
            - frontend
        restart: unless-stopped
networks:
    frontend:
        external: true

EOF

mkdir -p /opt/beyondcx/traefik/config
mkdir -p /opt/beyondcx/traefik/logs
mkdir -p /opt/beyondcx/traefik/config/conf

echo "DO_AUTH_TOKEN=" > /opt/beyondcx/traefik/.env

cat > /opt/beyondcx/traefik/config/traefik.yml <<EOF
global:
  checkNewVersion: false
  sendAnonymousUsage: false
log:
  level: DEBUG
api:
  dashboard: true
  insecure: true
entryPoints:
  web:
    address: :80
  websecure:
    address: :443
certificatesResolvers:
  doresolv:
    acme:
      email: "garbelo@gmail.com"
      storage: /var/traefik/certs/doresolv-acme.json
      caServer: 'https://acme-v02.api.letsencrypt.org/directory'
      keyType: EC256
      dnsChallenge:
          provider: digitalocean
          resolvers:
              - "8.8.8.8:53"
              - "1.1.1.1:53"
providers:
  docker:
      endpoint: "unix:///var/run/docker.sock"
      exposedByDefault: false
      network: frontend
  file:
    directory: /etc/traefik/conf/
    watch: true
EOF

cd /opt/beyondcx/traefik

PROXY_NETWORK="frontend"

if docker network inspect $PROXY_NETWORK > /dev/null 2>&1; then
	echo "red de traefik existe"
else
	docker network create $PROXY_NETWORK
fi

docker compose up -d

step "Levantado traefik "

docker compose ps 
docker compose logs

step "Recuerda, tienes que crear el DO_AUTH_TOKEN en el .env"



