#!/bin/bash

# Main script to manage Debian major version upgrade for fuss
# 
# Copyright (C) 2025-2026 FUSS Project <info@fuss.bz.it>
# Authors: Simone Piccardi <piccardi@truelite.it>
#
# 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; version 3 of the License.
#
# 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 or from the site that you downloaded it
# from; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA  02111-1307   USA
#

##
## General variables declaration
##

export SCRIPTS_DIR=${SCRIPTS_DIR:-/usr/share/fuss-release-updater/scripts}
export LOG_DIR=${LOG_DIR:-"/var/log/fuss-release-updater"}
export RES_DIR=${RES_DIR:-"/var/tmp/fuss-release-updater/results"}

# clean log and results
rm -f $LOG_DIR/*
rm -f $RES_DIR/*

# array for upgrade steps, declare them on sequence
# each value must refer to a script in SCRIPTS_DIR
declare -a STEPS
STEPS[1]=wait_unattended
STEPS[2]=missing_updates
STEPS[3]=fuss_client_update
STEPS[4]=disable_unattended
STEPS[5]=pre_upgrade_cleanup
STEPS[6]=set_apt_sources
STEPS[7]=first_upgrade
STEPS[8]=full_upgrade
STEPS[9]=reenable_timers
STEPS[10]=final_fuss_client

function do_error_exit () {
    # to be revised, now just write a message and exit
    if [ $ENDSTATUS = 'KO' ]; then
	echo $ERRMSG
	exit 1
    else
	echo "Steps successfully completed"
	echo "You need to reboot"
	exit 0
    fi
}

##
## Main 
##
ENDSTATUS="KO"
# following can be removed on package installation
test -d $LOG_DIR || mkdir -p $LOG_DIR || do_exit
test -d $RES_DIR || mkdir -p $RES_DIR || do_exit

if ! [ -d $SCRIPTS_DIR ]; then
    ERRMSG="Step 0 failed: missing $SCRIPTS_DIR step scripts directory"
    do_error_exit
fi

echo Release upgrade started at $(date "+%F %R") > $LOG_DIR/Upgrade-Start

ENDSTATUS="OK"
N_STEP=${#STEPS[*]}
for i in $(seq $N_STEP); do
    export STEP=$i
    export STEPRES=$RES_DIR/Step-$STEP
    STEPLOG=$LOG_DIR/"$i-${STEPS[$i]}"
    STEPEXE=$SCRIPTS_DIR/${STEPS[$i]}
    echo =========
    echo Executing step $STEP, script $STEPEXE
    echo =========
    screen -L -Logfile $STEPLOG $STEPEXE
    if [ $? != 0 ]; then
	echo "Error on screen $STEPEXE execution" >> $STEPLOG
	echo FAILED > $STEPRES
    fi
    RES=$(cat $STEPRES)
    echo "Step $i result is: $(cat $STEPRES)"
    if [ "$RES" != "PASSED" ]; then
	ENDSTATUS="KO"
	ERRMSG="Step $STEP failed: look at $STEPLOG"
	echo =========
	echo Step $STEP ended with error
	break
    fi
done

echo Release upgrade ended at $(date "+%F %R") > $LOG_DIR/Upgrade-End

do_error_exit
