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

DOCKER_DIR="/opt/hx-ki/docker"
cd "$DOCKER_DIR"

echo "=> Backup docker-compose.yml ..."
cp docker-compose.yml docker-compose.yml.bak_host80_$(date +%Y%m%d_%H%M%S)

echo "=> Entferne NUR Host-Port-80-Mappings aus docker-compose.yml ..."
awk '
  BEGIN {
    in_ports = 0
    ports_n = 0
  }
  {
    line = $0

    # Wenn wir gerade in einem ports:-Block sind
    if (in_ports) {
      if ($1 ~ /^-/) {
        # Host-Port 80? Dann überspringen
        if (line ~ /(^[[:space:]]*-[[:space:]]*"80:[0-9]+")|(^[[:space:]]*-[[:space:]]*80:[0-9]+)/) {
          next
        } else {
          ports_buf[++ports_n] = line
          next
        }
      } else {
        # Ende des ports:-Blocks
        in_ports = 0
        if (ports_n > 0) {
          print ports_header
          for (i = 1; i <= ports_n; i++) print ports_buf[i]
        }
        ports_n = 0
        # fällt jetzt durch und verarbeitet die aktuelle Zeile normal
      }
    }

    # Neuer ports:-Block
    if (line ~ /^[[:space:]]+ports:/) {
      in_ports = 1
      ports_header = line
      ports_n = 0
      next
    }

    # Normale Zeile
    print line
  }
' docker-compose.yml > docker-compose.yml.tmp

mv docker-compose.yml.tmp docker-compose.yml

echo "=> Orchester starten ..."
docker compose up -d --remove-orphans
