#!/bin/bash

# Copyright (C) 2018  Tetras Libre <Contact@Tetras-Libre.fr>
# Author: Beniamine, David <David.Beniamine@Tetras-Libre.fr>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

getip(){
    awk '/^lease/{IP=$2} /hardware ethernet/{gsub(";","",$3);if($3 == "'$1'"){print IP}}' \
        < /var/lib/dhcp/dhcpd.leases
}

# $1 : file|stdin
answer(){
    if [ -z "$1" ]
    then
        netcat $host $port
    else
        netcat $host $port < $1
    fi
}

IP=$(ip a | awk '/inet.*containers/ {print $2}' | cut -d / -f 1)
broadcast=$(ip a | awk '/inet.*eth1/ {print $4}' | cut -d / -f 1)
subnet=$(ip a | awk '/inet.*containers/ {print $2}' | cut -d / -f 1 | cut -d . -f 1-3)
host=$subnet.51
port=9999

while true
do
    LINE=`netcat -l $IP $port`
    #echo "$LINE"
    if [ $(echo "$LINE" | egrep -c "^([0-9a-f]{2}:?){6}$") -eq 1 ]
    then
        wakeonlan -i $broadcast "$LINE"
        sleep 3
        IPS=`getip $LINE`
        for ip in $IPS
        do
            ping -c 3 $ip
            if [ $? -eq 0 ]
            then
                echo "$ip" | answer
                break
            fi
        done
    elif [ "$LINE" == "getRegistry" ]
    then
        hostfile="/etc/registry/hosts"
        while read line
        do
            mac=$(echo $line | cut -d ' ' -f 2)
            IPS=$(getip $mac | sed -e 's/ /,/g')
            if [ -z "$IPS" ]
            then
                IPS="NA"
            fi
            echo "$line $IPS" >> $hostfile-$$
        done < $hostfile
        answer $hostfile-$$
        rm $hostfile-$$
    elif [[ "$LINE" =~ "getLog" ]]
    then
        cmd=$(echo $LINE | cut -d ' ' -f 1)
        name=$(echo $LINE | cut -d ' ' -f 2)
        logfile=$(ls /var/log/upgrade_all.sh_* | sort | tail -n 1)
        if [ "$name" == "$cmd" ]
        then
            answer $logfile
        else
            # Choose last log file with desired host
            logfile=$(grep -l $name /var/log/upgrade_all.sh_* | sort | tail -n 1)
            tempfile="/tmp/$$"
            # Extract the pertinent part of the log
            awk 'BEGIN{IN=0} /Begin host/{if($4=="'$name'"){IN=1}} {if(IN){print $0}} /End host/{if($4=="'$name'"){IN=0}}' \
                $logfile > $tempfile
            if [ ! -s $tempfile ]
            then
                # Log file is empty, this happens when we are starting an upgrade on a specific host
                cp $logfile $tempfile
            fi
            answer $tempfile
            rm $tempfile
        fi
    elif [[ "$LINE" =~ "upgrade" ]]
    then
        DIR="$(realpath $(dirname $0))/../../registry/scripts/"
        subactions="$(echo $LINE | sed -e 's/^upgrade//' -e 's/All//')"
        nohup $DIR/upgrade_all.sh $subactions &
        echo "Started 'upgrade_all.sh $subactions' in background on $(date)" | answer
    elif [[ "$LINE" =~ "reboot" ]]
    then
        mac=$(echo $line | cut -d ' ' -f 2)
        IPS=$(getip $mac | sed -e 's/ /,/g')
        for $ip in $IPS
        do
            ssh $ip "reboot"
        done
        answer "Redémarrage demandé, attendez une à deux minutes avant d'essayer de vous connecter"
    fi
done