#!/bin/bash

echo "RUN $(basename "$0") ==="

DIR=$(realpath $(dirname $0)/..)
if [ ! -e $DIR/main.env ]
then
    echo "Please copy in racine of NoCloud Auto Installer main.env.sample to main.env and edit it"
    exit 1
else
    echo "Environment file loaded"
fi
. $DIR/main.env
unset DOMAIN

# Add systemd script to control container boot order
order_systemd_file="/etc/systemd/system/docker-order.service"
if [ ! -e "$order_systemd_file" ]; then
    cp ${DIR}${order_systemd_file} $order_systemd_file
    systemctl daemon reload
fi
systemctl enable docker-order

# Services maintenance
cd /home/dockerweb

git config --global --add safe.directory '/home/dockerweb/\*'

if [ ! -d "maintenance" ]; then
  git clone https://gitlab.tetras-libre.fr/nocloud/docker/maintenance.git
  cd /home/dockerweb/maintenance
  cp .env.sample .env
else
  cd /home/dockerweb/maintenance
  git pull
fi
domain=$(bash $DIR/checks/list_domains.sh | grep -v '===' | sed "s/^/\`/" | sed "s/$/\`/" | paste -sd "," -)
sed -i "s/HOSTS=.*/HOSTS=$domain/" .env

# install dig is not
if ! dpkg -s bind9-dnsutils > /dev/null; then
   echo "install bind9-dnsutils"
   apt-get install bind9-dnsutils
else
   echo "bind9-dnsutils is alredy installed"
fi

iptetrix=$(dig tetrix.tetras-libre.fr | awk '/;; ANSWER SECTION:/ {getline; print "`" $5 "`"}')
sed -i "s/IGNORE_IPS=.*/IGNORE_IPS=$iptetrix/" .env

docker-compose up -d --build

# Services ban
cd /home/dockerweb/

if [ ! -d "ban" ]; then
  git clone https://gitlab.tetras-libre.fr/nocloud/docker/ban.git
  cd /home/dockerweb/ban
  chown root:dockerweb /home/dockerweb/ban
  chmod g+w /home/dockerweb/ban
  cp .env.sample .env
else
  cd /home/dockerweb/ban
  chown root:dockerweb /home/dockerweb/ban
  chmod g+w /home/dockerweb/ban
  git pull
fi

# MAJ traefik
cd /home/dockerweb/traefik
git pull
find /home/dockerweb -name "docker-compose.yml" | while read file; do
    dir=$(dirname $file)
    echo $dir
    cd $dir
    if [ ! -e "disabled" ] &&  ! [[ "$dir" =~ "tetras-bi" ]] ; then
        git pull
        docker-compose pull
        docker-compose build
        docker-compose down
        docker-compose up -d
        if [ -e "upgrade.sh" ] && [ -x "upgrade.sh" ] ; then
            echo "Running upgrade script for $dir"
            ./upgrade.sh
            echo "Done $?"
        fi
    fi
    cd -
done

bash $DIR/upgrade/traefik_fail2ban.sh
