#!/usr/bin/env bash

# ==============================================
#
# This is second part of switch network between WAN and 4G
# This script is Aquila part
#
# ==============================================
# if tetrix reachable
#    if etatCourant != Normal
#          currentStatre = Normal
#          stoppedAquilaService
# else
#    if currentStatre != Backup
#          currentStatre = Backup
#          startAquilaService
# ==============================================


tetrixPublicIPOnOVH="109.190.180.230"

URL="https://$tetrixPublicIPOnOVH"

stateFile="/opt/net-state"
reverseSSHproxyPath="/home/dockerweb/reverse-ssh-proxy"

# Send HTTP request on tetrix to get status code
HTTP_STATUS=$(curl -o /dev/null -w "%{http_code}\n" -s -k  $URL)


if [[ -f "$stateFile" ]]; then

    $state=`cat $stateFile`
    # check if tetrix is reachable (status code 200)
    if [ $HTTP_STATUS -eq 200 ]; then
        if [[ $state != "normal" ]]; then
            # Switch on normal mode
            cd $reverseSSHproxyPath
            docker-compose down
            echo "normal" > "$stateFile"
        fi
    else
        if [[ $state = "normal" ]]; then
            # Switch on back up mode
            cd $reverseSSHproxyPath
            docker-compose up -d
            echo "backup" > "$stateFile"
        fi
    fi
else
    echo "normal" > "$stateFile"
fi