#!/bin/bash
# This file is part of the FUSS project.
# Copyright (C) 2022 The FUSS Project <info@fuss.bz.it>
# Author: Marco Marinello <contact-nohuman@marinello.bz.it>
# 		Claudio Cavalli <info@fuss.bz.it>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
# Run fuss-client -U if an update was installed by unattended upgrades
# and the client is already joined to the domain

fc_option=""
LOCKFILE="/var/lock/fuss-client-unattended.lock"
UPTR=/var/lib/fuss-client/upgrade-trigger

# Exit if fuss-client has never been executed
test -e /etc/ansible/facts.d/fuss_client.fact || exit 0

# Exit if the update was already executed and the ldap certificate has not
# changed
if [ ! -e "$UPTR" ] && ldapsearch -x >/dev/null 2>&1; then
    exit 0
fi

if [ -e "$UPTR" ] && [ -e "$LOCKFILE" ]; then
    exit 0
fi

# Run fuss-client -U if the client is  joined to the domain
if [ -e "/etc/fuss-client/server.conf" ]; then

        if dpkg -s fuss-children fuss-kids fuss-education >/dev/null 2>&1 ; then    
	    fc_option="-U"
	
        else
	    fc_option="-U --light"
	
        fi

# Run fuss-client --standalone .. if the client is not joined to the domain
elif dpkg -s fuss-children fuss-kids fuss-education  fuss-unofficial >/dev/null 2>&1 ; then
    fc_option="--standalone --unofficial"

elif dpkg -s fuss-children fuss-kids fuss-education >/dev/null 2>&1 ; then  
    fc_option="--standalone"

elif dpkg -s fuss-unofficial >/dev/null 2>&1 ; then  
    fc_option="--standalone --light --unofficial"
    
else
    fc_option="--standalone --light"
    
fi    

# Lock the upgrade process: if apt takes more
# than an hour, no other execution will start.
echo $$ > $LOCKFILE

LOGFILE="/var/log/fuss-client-unattended-$(date +%Y-%m-%d-%H-%M).log"

echo "Unattended execution of fuss-client started on $(date)" > $LOGFILE

# Wait for any packaging-related process to finish
echo "$(date) - start loop to wait apt to be finished" >> $LOGFILE
while ps -C apt-get,apt,dpkg > /dev/null ; do
        sleep 5
done
echo "$(date) - apt finished, run fuss-client" >> $LOGFILE

# Run fuss-client 
fuss-client $fc_option >> $LOGFILE 2>&1

# No need to remove the trigger file as it will be removed by fuss-client itself
rm $LOCKFILE
