#!/bin/bash

export NEEDRESTART_MODE=a
export DEBIAN_FRONTEND=noninteractive

export var1; export var2

mTITLE="Docker Orchestration"
bkTTITLE="Sistema Automatizado de Orquestração de Containers"

if [ -n "$SUDO_USER" ]; then
  source /home/$SUDO_USER/.index.sh
else
  source $HOME/.index.sh
fi

webadress="$link000"
github="$webadress/docker/"
common_functions_url="${github}X-COMMON-BASE.sh"

function get_script_map {
  # Mapeamento centralizado img_base → script
  case "$1" in
    # modelstools
    "dashdot") echo "61-dashdot" ;;
    "active-directory"|"domain") echo "02-domain" ;;
    "myspeed"|"wan-speed-test") echo "20-myspeed-tracker" ;;
    "openspeedtest"|"lan-speed-test") echo "16-openspeedtest" ;;
    "pihole") echo "01-pihole" ;;
    "xpra") echo "45-xpra-virt-manager" ;;

    # contratos0
    "filebrowser") echo "28-filebrowser" ;;
    "homarr"|"homarr-web-panel") echo "60-homarr" ;;
    "pentest") echo "09-pentest" ;;
    "unifi") echo "03-unifi-net" ;;
    "reverse-proxy") echo "33-reverseproxy" ;;
    "openfire") echo "27-openfire" ;;
    "onlyoffice") echo "34-onlyoffice" ;;
    "tailscale") echo "13-tailscale" ;;
    "qdir") echo "74-qdirstat" ;;
    "sist2"|"elastic-search-gui") echo "80-sist2" ;;
    "nut") echo "06-nut-gui" ;;
    "nobreak-sms") echo "11-SMS-PV" ;;
    "kuma") echo "15-kuma" ;;
    "plocate") echo "24-plocate" ;;

    # general
    "ferdium") echo "25-ferdium" ;;
    "nextcloud") echo "26-nextcloud" ;;
    "ntfy") echo "30-ntfy_server" ;;
    "apache2") echo "36-generic_apache" ;;
    "cups") echo "10-cups" ;;
    "ftp") echo "37-ftp-server" ;;
    "syncthing") echo "42.0-syncthing" ;;
    "chromium"|"chromium-browser") echo "17-Chromium" ;;
    "chrome-browser") echo "18-google-chrome" ;;

    # database
    "mysql") echo "04-mysql" ;;
    "mariadb") echo "29-mariadb" ;;
    "oraclexe21c") echo "05-oracle_xe" ;;
    "elasticsearch"|"elasticsearch-db") echo "78-elasticsearch" ;;

    # personal
    "luanti") echo "12-luanti-server" ;;
    "minecraft") echo "31-minecraft-server" ;;
    "dwservice") echo "38-ssh-dw" ;;
    "jellyfin") echo "19-jellyfin" ;;
    "qbittorrent") echo "21-qbittorrent" ;;
    "domain-test") echo "58-domain-test" ;;
    "swc") echo "07-simple-web-chat" ;;
    "docker-macos") echo "32-macOS-in-Docker" ;;
    "docker-windows") echo "35-Windows-in-Docker" ;;
    "honeygain") echo "08-honeygain" ;;
    "kasm") echo "14-kasm" ;;
    "aptcache") echo "22-apt-cacher" ;;
    "meshstatic") echo "23-meshstatic-web" ;;

    # more
    "adguard") echo "39-adguardhome" ;;
    "homeassistant") echo "40-home-assistant" ;;
    "mosquitto") echo "41-mosquitto" ;;
    "wyl") echo "43-watch_your_lan" ;;
    "motion") echo "44-motion" ;;
    "wordpress") echo "46-wordpress" ;;
    "weather-station") echo "47-meteo" ;;
    "php_apache") echo "48-php_apache" ;;
    
    # frigate
    "frigate-intel") echo "08.0-frigate-intel" ;;
    "frigate-nvidia") echo "08.1-frigate-nvidia" ;;
    "frigate-amd") echo "08.2-frigate-amd" ;;
    "frigate-web-lpr") echo "08.3-frigate-web-lpr" ;;

    *) echo "" ;;
  esac
}

function start {
  if [ -f /srv/lockfile ]; then
    echo "LOCKFILE DETECTADO!"

    if [ ! -f /srv/containers.yaml ]; then
      echo "ERRO: containers.yaml nao encontrado!"
      sudo rm /srv/lockfile
      exit 1
    fi

    echo "Modo automatico ativado. Processando containers..."
    sleep 2

    # Pega todas as img_base únicas do containers.yaml
    mapfile -t unique_images < <(yq -r '[.[] | .img_base] | unique | .[]' /srv/containers.yaml)

    if [ ${#unique_images[@]} -eq 0 ]; then
      echo "ERRO: Nenhuma imagem encontrada no containers.yaml!"
      sudo rm /srv/lockfile
      exit 1
    fi

    echo "Imagens encontradas: ${#unique_images[@]}"
    for img in "${unique_images[@]}"; do
      count=$(yq -r "[.[] | select(.img_base == \"$img\")] | length" /srv/containers.yaml)
      echo "  • $img ($count container(s))"
    done
    echo ""

    # Para cada img_base, processa via script correspondente
    for img_base in "${unique_images[@]}"; do
      if [ -z "$img_base" ] || [ "$img_base" = "null" ]; then
        continue
      fi

      script_to_run=$(get_script_map "$img_base")

      if [ -n "$script_to_run" ]; then
        echo "============================================"
        echo "Processando: $img_base"
        echo "Script: $script_to_run"

        # Mostra containers que serão processados
        containers=$(yq -r "to_entries[] | select(.value.img_base == \"$img_base\") | .key" /srv/containers.yaml)
        echo "Containers:"
        echo "$containers" | while read -r cont; do
          echo "  • $cont"
        done
        echo "============================================"

        if curl -sSL "$github$script_to_run" | tee "/tmp/$script_to_run" >/dev/null; then
          sudo bash "/tmp/$script_to_run"
          echo "✓ Processado: $img_base"
        else
          echo "✗ ERRO ao baixar: $script_to_run"
        fi

        sleep 2
      else
        echo "⚠️  AVISO: Nenhum script mapeado para: $img_base"
      fi
    done

    echo ""
    echo "============================================"
    echo "Processamento automático concluído!"
    echo "Removendo lockfile..."
    sudo rm /srv/lockfile
    exit 0
  fi

  if ! var0=$(dialog --title "$mTITLE" --backtitle "$bkTTITLE" --menu "" 0 0 0 \
  1 'Modelo & Ferramentas' \
  2 'Somente Contrato' \
  3 'Servicos Gerais' \
  4 'Bancos de Dados' \
  5 'Outros' \
  X 'Sair' 2>&1 >/dev/tty ); then
    exit
  fi

  case "$var0" in
  1) modelstools ; start ;;
  2) contratos0 ; start ;;
  3) general ; start ;;
  4) database ; start ;;
  5) personal ; start ;;
  X) exit ;;
  esac
}

function contratos0 {
  if ! var0=$(dialog --title "$mTITLE" --backtitle "$bkTTITLE" --menu "" 0 0 0 \
  1 'File Browser' \
  2 'Homarr' \
  3 'PenTest' \
  4 'UniFi Network' \
  5 'Reverse Proxy' \
  6 'OpenFire (Spark)' \
  7 'OnlyOffice' \
  8 'Tailscale CLIENT' \
  9 'QDir Stat' \
  10 'Sist2 Indexer' \
  11 'Network UPS Tools Gui (L)' \
  12 'SMS PowerViewer' \
  13 'Kuma' \
  14 'pLocate (W/L)' \
  X '<' 2>&1 >/dev/tty ); then
    return
  fi

  case "$var0" in
  1) curl -sSL "$github"28-filebrowser | tee /tmp/filebrowser >/dev/null; sudo bash /tmp/filebrowser ;;
  2) curl -sSL "$github"60-homarr | tee /tmp/homarr >/dev/null; sudo bash /tmp/homarr ;;
  3) curl -sSL "$github"09-pentest | tee /tmp/pentest >/dev/null; sudo bash /tmp/pentest ;;
  4) curl -sSL "$github"03-unifi-net | tee /tmp/unifi >/dev/null; sudo bash /tmp/unifi ;;
  5) curl -sSL "$github"33-reverseproxy | tee /tmp/apacherp >/dev/null; sudo bash /tmp/apacherp ;;
  6) curl -sSL "$github"27-openfire | tee /tmp/openfire >/dev/null; sudo bash /tmp/openfire ;;
  7) curl -sSL "$github"34-onlyoffice | tee /tmp/ooffice >/dev/null; sudo bash /tmp/ooffice ;;
  8) curl -sSL "$github"13-tailscale | tee /tmp/tailscale >/dev/null; sudo bash /tmp/tailscale ;;
  9) curl -sSL "$github"74-qdirstat | tee /tmp/qdirstat >/dev/null; sudo bash /tmp/qdirstat ;;
  10) curl -sSL "$github"80-sist2 | tee /tmp/sist2 >/dev/null; sudo bash /tmp/sist2 ;;
  11) curl -sSL "$github"06-nut-gui | tee /tmp/nut-gui >/dev/null; sudo bash /tmp/nut-gui ;;
  12) curl -sSL "$github"11-SMS-PV | tee /tmp/SMS >/dev/null; sudo bash /tmp/SMS ;;
  13) curl -sSL "$github"15-kuma | tee /tmp/kuma >/dev/null; sudo bash /tmp/kuma ;;
  14) curl -sSL "$github"24-plocate | tee /tmp/plocate >/dev/null; sudo bash /tmp/plocate ;;
  X) return ;;
  esac
}

function modelstools {
  if ! var0=$(dialog --title "$mTITLE" --backtitle "$bkTTITLE" --menu "" 0 0 0 \
  1 'DashDot' \
  2 'Active Directory' \
  3 'MySpeed  Test WAN' \
  4 'OpenSpeedTest LAN' \
  5 'PiHole' \
  6 'XPRA VM MGR' \
  7 'AdGuard Home' \
  8 'Watch Your LAN' \
  X '<' 2>&1  >/dev/tty ); then
    return
  fi

  case "$var0" in
  1) curl -sSL "$github"61-dashdot | tee /tmp/dashdot >/dev/null; sudo bash /tmp/dashdot ;;
  2) curl -sSL "$github"02-domain | tee /tmp/domain >/dev/null; sudo bash /tmp/domain ;;
  3) curl -sSL "$github"20-myspeed-tracker | tee /tmp/myspeed >/dev/null; sudo bash /tmp/myspeed ;;
  4) curl -sSL "$github"16-openspeedtest | tee /tmp/speedtest >/dev/null; sudo bash /tmp/speedtest ;;
  5) curl -sSL "$github"01-pihole | tee /tmp/pihole >/dev/null; sudo bash /tmp/pihole ;;
  6) curl -sSL "$github"45-xpra-virt-manager | tee /tmp/45-xpra-virt-manager >/dev/null; sudo bash /tmp/45-xpra-virt-manager ;;
  7) curl -sSL "$github"39-adguardhome | tee /tmp/39-adguardhome >/dev/null; sudo bash /tmp/39-adguardhome ;;
  8) curl -sSL "$github"43-watch_your_lan | tee /tmp/watch_your_lan >/dev/null; sudo bash /tmp/watch_your_lan ;;
  X) return ;;
  esac
}

function general {
  if ! var0=$(dialog --title "$mTITLE" --backtitle "$bkTTITLE" --menu "" 0 0 0 \
  1 'Ferdium (RAMBOX)' \
  2 'NextCloud' \
  3 'ntfy' \
  4 'Servidor Apache' \
  5 'Servidor CUPS' \
  6 'Servidor FTP' \
  7 'Syncthing CLIENT' \
  8 'Chromium Browser' \
  9 'Home Assistant' \
  10 'Mosquitto MQTT' \
  11 'Motion NVR' \
  12 'Wordpress' \
  13 'Frigate (Intel)' \
  14 'Frigate (NVIDIA)' \
  15 'Frigate (AMD)' \
  16 'Frigate Web LPR' \
  17 'Servidor PHP Apache' \
  X '<' 2>&1  >/dev/tty ); then
    return
  fi

  case "$var0" in
  1) curl -sSL "$github"25-ferdium | tee /tmp/ferdium >/dev/null; sudo bash /tmp/ferdium ;;
  2) curl -sSL "$github"26-nextcloud | tee /tmp/nextcloud >/dev/null; sudo bash /tmp/nextcloud ;;
  3) curl -sSL "$github"30-ntfy_server | tee /tmp/ntfy_server >/dev/null; sudo bash /tmp/ntfy_server ;;
  4) curl -sSL "$github"36-generic_apache | tee /tmp/genericapache >/dev/null; sudo bash /tmp/genericapache ;;
  5) curl -sSL "$github"10-cups | tee /tmp/cups >/dev/null; sudo bash /tmp/cups ;;
  6) curl -sSL "$github"37-ftp-server | tee /tmp/ftp-server >/dev/null; sudo bash /tmp/ftp-server ;;
  7) curl -sSL "$github"42.0-syncthing | tee /tmp/syncthing >/dev/null; sudo bash /tmp/syncthing ;;
  8) curl -sSL "$github"17-Chromium | tee /tmp/Chromium >/dev/null; sudo bash /tmp/Chromium ;;
  9) curl -sSL "$github"40-home-assistant | tee /tmp/home-assistant >/dev/null; sudo bash /tmp/home-assistant ;;
  10) curl -sSL "$github"41-mosquitto | tee /tmp/mosquitto >/dev/null; sudo bash /tmp/mosquitto ;;
  11) curl -sSL "$github"44-motion | tee /tmp/motion >/dev/null; sudo bash /tmp/motion ;;
  12) curl -sSL "$github"46-wordpress | tee /tmp/wordpress >/dev/null; sudo bash /tmp/wordpress ;;
  13) curl -sSL "$github"08.0-frigate-intel | tee /tmp/frigate-intel >/dev/null; sudo bash /tmp/frigate-intel ;;
  14) curl -sSL "$github"08.1-frigate-nvidia | tee /tmp/frigate-nvidia >/dev/null; sudo bash /tmp/frigate-nvidia ;;
  15) curl -sSL "$github"08.2-frigate-amd | tee /tmp/frigate-amd >/dev/null; sudo bash /tmp/frigate-amd ;;
  16) curl -sSL "$github"08.3-frigate-web-lpr | tee /tmp/frigate-web-lpr >/dev/null; sudo bash /tmp/frigate-web-lpr ;;
  17) curl -sSL "$github"48-php_apache | tee /tmp/php_apache >/dev/null; sudo bash /tmp/php_apache ;;
  X) return ;;
  esac
}

function database {
  if ! var0=$(dialog --title "$mTITLE" --backtitle "$bkTTITLE" --menu "" 0 0 0 \
  1 'MySQL' \
  2 'MariaDB' \
  3 'OracleXE 21C' \
  4 'ElasticSearch 7.17.22' \
  X '<' 2>&1  >/dev/tty ); then
    return
  fi

  case "$var0" in
  1) curl -sSL "$github"04-mysql | tee /tmp/mysql >/dev/null; sudo bash /tmp/mysql ;;
  2) curl -sSL "$github"29-mariadb | tee /tmp/mariadb >/dev/null; sudo bash /tmp/mariadb ;;
  3) curl -sSL "$github"05-oracle_xe | tee /tmp/oracle_xe >/dev/null; sudo bash /tmp/oracle_xe ;;
  4) curl -sSL "$github"78-elasticsearch | tee /tmp/elasticsearch >/dev/null; sudo bash /tmp/elasticsearch ;;
  X) return ;;
  esac
}

function personal {
  if ! var0=$(dialog --title "$mTITLE" --backtitle "$bkTTITLE" --menu "" 0 0 0 \
  1 'Luanti Server' \
  2 'Minecraft Server' \
  3 'SSH DW Backup (L)' \
  4 'Jellyfin' \
  5 'qBitTorrent' \
  6 'Active Directory (BETA)' \
  7 'Simple Chat Server' \
  8 'macOS on Docker' \
  9 'Weather Station' \
  X '<' 2>&1  >/dev/tty ); then
    return
  fi

  case "$var0" in
  1) curl -sSL "$github"12-luanti-server | tee /tmp/luanti >/dev/null; sudo bash /tmp/luanti ;;
  2) curl -sSL "$github"31-minecraft-server | tee /tmp/minecraft >/dev/null; sudo bash /tmp/minecraft ;;
  3) curl -sSL "$github"38-ssh-dw | tee /tmp/ssho >/dev/null; sudo bash /tmp/ssho ;;
  4) curl -sSL "$github"19-jellyfin | tee /tmp/jellyfin >/dev/null; sudo bash /tmp/jellyfin ;;
  5) curl -sSL "$github"21-qbittorrent | tee /tmp/qbittorrent >/dev/null; sudo bash /tmp/qbittorrent ;;
  6) curl -sSL "$github"58-domain-test | tee /tmp/dtest >/dev/null; sudo bash /tmp/dtest ;;
  7) curl -sSL "$github"07-simple-web-chat | tee /tmp/chatsimple >/dev/null; sudo bash /tmp/chatsimple ;;
  8) curl -sSL "$github"32-macOS-in-Docker | tee /tmp/macOS >/dev/null; sudo bash /tmp/macOS ;;
  9) curl -sSL "$github"47-meteo | tee /tmp/meteo >/dev/null; sudo bash /tmp/meteo ;;
  X) return ;;
  esac
}

function ensure_common {
  echo "Atualizando common-functions.sh..."
  if ! curl -sSL --connect-timeout 5 --max-time 0 --retry 3 --retry-delay 2 "$common_functions_url" | tee /tmp/common-functions.sh >/dev/null && [ -s /tmp/common-functions.sh ]; then
    echo "ERRO: Falha ao baixar common-functions.sh, utilizando a versao local se existente..."
    sleep 2
  fi
}

if ! command -v yq >/dev/null 2>&1; then
  clear; echo "yq não foi encontrado no sistema"; sleep 3
  return 1
fi

if ! docker network inspect macvlan &>/dev/null; then
    curl -sSL --connect-timeout 5 --max-time 0 --retry 3 --retry-delay 2 $link103 | sudo bash
fi

ensure_common
start
