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

if [[ $# -lt 1 || $# -gt 2 ]]; then
  echo "Usage: $0 <route-name> [domain]"
  echo "Example: $0 webpage4 mydomain.de"
  exit 1
fi

NAME="$1"
DOMAIN="${2:-mydomain.de}"

if [[ ! "$NAME" =~ ^[a-zA-Z0-9][a-zA-Z0-9_-]*$ ]]; then
  echo "Invalid route name: $NAME"
  echo "Allowed: letters, numbers, underscore, dash"
  exit 1
fi

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
ROOT_BASE="${ROOT_BASE:-/srv/ikfreunde}"
COMPOSE_FILE="${COMPOSE_FILE:-$ROOT_DIR/administration/docker-compose.traefik-routes.yml}"
ROOT="${ROOT_BASE}/${NAME}"

if [[ ! -f "$COMPOSE_FILE" ]]; then
  echo "Compose file not found: $COMPOSE_FILE"
  exit 1
fi

mkdir -p "$ROOT"

if [[ ! -f "$ROOT/ikfreunde.com.html" ]]; then
  cp "$ROOT_DIR/website/ikfreunde.com.html" "$ROOT/ikfreunde.com.html"
  echo "Created: $ROOT/ikfreunde.com.html"
fi

if [[ ! -f "$ROOT/site-content.de.json" ]]; then
  cp "$ROOT_DIR/website/content/site-content.de.json" "$ROOT/site-content.de.json"
  echo "Created: $ROOT/site-content.de.json"
fi

if rg -q "^  ${NAME}:$" "$COMPOSE_FILE"; then
  echo "Service '${NAME}' already exists in $COMPOSE_FILE"
else
  block_file="$(mktemp)"
  tmp_file="$(mktemp)"

  cat > "$block_file" <<YAML

  ${NAME}:
    build:
      context: ..
      dockerfile: administration/Dockerfile
    container_name: ikfreunde-${NAME}
    volumes:
      - ${ROOT}/ikfreunde.com.html:/app/website/ikfreunde.com.html
      - ${ROOT}/site-content.de.json:/app/website/content/site-content.de.json
    restart: unless-stopped
    networks:
      - proxy
    labels:
      - traefik.enable=true
      - traefik.http.routers.${NAME}.rule=Host(\`${DOMAIN}\`) && PathPrefix(\`/${NAME}\`)
      - traefik.http.routers.${NAME}.entrypoints=websecure
      - traefik.http.routers.${NAME}.tls=true
      - traefik.http.services.${NAME}.loadbalancer.server.port=4173
      - traefik.http.routers.${NAME}.middlewares=${NAME}-slash,${NAME}-strip
      - traefik.http.middlewares.${NAME}-slash.redirectregex.regex=^https?://([^/]+)/${NAME}$
      - traefik.http.middlewares.${NAME}-slash.redirectregex.replacement=https://\$\${1}/${NAME}/
      - traefik.http.middlewares.${NAME}-slash.redirectregex.permanent=true
      - traefik.http.middlewares.${NAME}-strip.stripprefix.prefixes=/${NAME}
YAML

  awk -v block_file="$block_file" '
    BEGIN { inserted = 0 }
    /^networks:/ && inserted == 0 {
      while ((getline line < block_file) > 0) print line
      close(block_file)
      inserted = 1
    }
    { print }
    END {
      if (inserted == 0) {
        while ((getline line < block_file) > 0) print line
        close(block_file)
      }
    }
  ' "$COMPOSE_FILE" > "$tmp_file"

  mv "$tmp_file" "$COMPOSE_FILE"
  rm -f "$block_file"

  echo "Inserted service '${NAME}' into $COMPOSE_FILE"
fi

echo
echo "Next steps:"
echo "1) docker compose -f $COMPOSE_FILE up -d --build"
echo "2) Open: https://${DOMAIN}/${NAME}/"
