#!/bin/bash
set -e
URL_FOR_DOWNLOAD=https://infr-runner.daywave.ru/

if ! [ -f ".env" ]; then
    echo "downloading env..."
    curl -fsSL "${URL_FOR_DOWNLOAD}/.env" -o .env
    echo "please fill .env and rerun script"
    exit 0
fi
if [ -f .env ]; then
  export $(grep -v '^#' .env | xargs)
  echo "PACKMATE_LOCAL_IP=$(ip -f inet addr show $NET_INTERFACE | sed -En -e 's/.*inet ([0-9.]+).*/\1/p')">>.env
  export $(grep -v '^#' .env | xargs)
fi

if command -v docker >/dev/null 2>&1; then
  if ! command -v docker compose >/dev/null 2>&1; then
    echo "[!] docker v1 installed! reinstalling to docker v2..."
    sudo systemctl stop docker
    sudo apt-get remove -y docker docker-engine docker.io containerd runc
    sudo apt-get autoremove -y
    sudo rm -rf /var/lib/docker /var/lib/containerd
  fi
else
    echo "[!] docker is not installed! installing docker..."
fi
if ! command -v docker >/dev/null 2>&1; then
    curl -fsSL https://get.docker.com -o install-docker.sh
    sudo bash install-docker.sh >/dev/null
    if [ ! "$(id -u)" -eq 0 ]; then
        dockerd-rootless-setuptool.sh install
    fi
fi

if [ ! -d "./Packmate_stuff" ]; then
    mkdir ./Packmate_stuff
fi

if [ ! -f "./Packmate_stuff/postgresql.conf" ]; then
    curl -fsSL ${URL_FOR_DOWNLOAD}/postgresql.conf -o ./Packmate_stuff/postgresql.conf
fi

if [ ! -f "./Packmate_stuff/update_db_config.sh" ]; then
    curl -fsSL ${URL_FOR_DOWNLOAD}/update_db_config.sh -o ./Packmate_stuff/update_db_config.sh
fi


if [ -f ".infr.compose.yaml" ]; then
    output=$(docker compose -f .infr.compose.yaml logs)
    if [ -z "$output" ]; then
        echo "found compose, running infr..."
        if docker compose -f .infr.compose.yaml up -d; then
          echo "compose runned successfully, runing services and setup packmate..."
          echo "whaiting 15 seconds for packmate start..."
          sleep 15
        else
          echo "compose run failed"
          exit 1
        fi
    else
        echo "compose already runned, runing services and setup packmate..."
    fi
else
    echo "downloading compose..."
    curl -fsSL ${URL_FOR_DOWNLOAD}/docker-compose.yaml -o .infr.compose.yaml
    echo "compose downloaded, running infr..."
    if docker compose -f .infr.compose.yaml up -d; then
      echo "compose runned successfully, runing services and setup packmate..."
      echo "whaiting 15 seconds for packmate start..."
      sleep 15
    else
      echo "compose run failed"
      exit 1
    fi
fi

TOKEN=$(echo "$WEB_LOGIN:$WEB_PASSWORD" | base64)
for service_path in "$SERVICES_DIR"/*/; do
    [ -d "$service_path" ] || continue
    service_name=$(basename "$service_path")
    cd $service_path
    output=$(docker compose logs)
    if [ -z "$output" ]; then
        if docker compose up -d --build; then
            echo "service $service_name runned successfully"
        else
            echo "service $service_name don't start"
            exit 1;
        fi
    else
        echo "service $service_name already runned"
    fi
    docker compose ps | awk 'NR>2 && $NF != "" { split($NF, a, "->"); split(a[1], b, ":"); print $1, b[2] }' | while read service port; do
        http_code=$(curl -i -X POST "http://127.0.0.1:65000/api/service/" \
            -H "Authorization: Basic $TOKEN" \
            -H "Accept-Encoding: gzip, deflate, br" \
            -H "Content-Type: application/json" \
            -d "{\"name\":\"$service_name\",\"port\":$port,\"http\":true,\"urldecodeHttpRequests\":true,\"mergeAdjacentPackets\":true,\"parseWebSockets\":true,\"decryptTls\":true}")
        if [ "$http_code" -eq 200 ]; then
            echo "service $service_name added to packmate"
        elif [ "$http_code" -eq 500 ]; then
            echo "port $port already binded in packmate, can't add it"
        else
            echo "unknown code $http_code"
        fi
    done
done
echo "all services runned correctly"

