#!/usr/bin/env bash
#--label "traefik.http.routers.${UUID}.middlewares=cors-headers@file" \
echo "Start N8N container ${UUID}"

# Get the hostname of the machine
HOSTNAME=$(hostname)

mkdir -p /4server/data/${UUID}/n8n
mkdir -p /4server/data/${UUID}/data
mkdir -p /4server/data/${UUID}/backup

chmod 777 /4server/data/${UUID}/n8n
chmod 777 /4server/data/${UUID}/data
chmod 777 /4server/data/${UUID}/backup

# Stop the container if it exists
if docker ps -a --format '{{.Names}}' | grep -q "^${UUID}$"; then
  echo "$(date '+%Y-%m-%d %H:%M') - stopping existing container $UUID"
  docker stop "$UUID"
  docker rm "$UUID"
fi



docker run -d \
  --name "$UUID" \
  -p 5678 \
  --cap-add=SYS_ADMIN \
  --security-opt seccomp=unconfined \
  --restart=always \
  -e N8N_EMAIL_MODE=smtp \
  -e N8N_SMTP_HOST="smtp.strato.de" \
  -e N8N_SMTP_PORT=587 \
  -e N8N_SMTP_USER="n8n@odoo4projects.com" \
  -e N8N_SMTP_PASS="Airbus12N@N" \
  -e N8N_SMTP_SENDER="n8n <n8n@odoo4projects.com>" \
  -e N8N_SMTP_SSL=false \
  -e N8N_HOST="${UUID}.odoo4projects.com" \
  -e N8N_PORT=5678 \
  -e N8N_PROTOCOL=https \
  -e N8N_FORMDATA_FILE_SIZE_MAX=3000 \
  -e N8N_TRUST_PROXY=true \
  -e NODE_ENV=production \
  -e EXECUTIONS_PRUNE=true \
  -e EXECUTIONS_PRUNE_MAX_AGE=48 \
  -e WEBHOOK_URL="https://${UUID}.odoo4projects.com/" \
  -e GENERIC_TIMEZONE="UTC-3" \
  -e N8N_BLOCK_ENV_ACCESS_AND_PROCESS_INFORMATION=true \
  -e N8N_CUSTOM_EXTENSIONS="/usr/local/share/n8n/custom" \
  -v "/4server/data/${UUID}/n8n:/home/node/.n8n" \
  -v "/4server/data/${UUID}/data:/data" \
  -v "/4server/data/${UUID}/backup:/backup" \
  --label "traefik.enable=true" \
  --label "traefik.http.routers.${UUID}.rule=Host(\`${UUID}.odoo4projects.com\`)" \
  --label "traefik.http.routers.${UUID}.entrypoints=web,websecure" \
  --label "traefik.http.routers.${UUID}.tls=true" \
  --label "traefik.http.routers.${UUID}.tls.certresolver=production" \
  --label "traefik.http.services.${UUID}.loadbalancer.server.port=5678" \
  --network 4server_4projects \
  docker.odoo4projects.com/4projects/n8n:release

echo "Started $1"
