#!/bin/bash
release_file=/etc/os-release
logfile=/var/log/updater.log
errorlog=/var/log/updater_errors.log

check_exit_status() {
    local status=$?
    local command_name=$1
    if [ $status -ne 0 ]; then
        echo "$(date): An error occurred during $command_name (exit code: $status). Check $errorlog." | tee -a $logfile
        exit 1
    fi
}

echo "$(date): Starting update process..." >> $logfile

if grep -q "Ubuntu" $release_file || grep -q "Debian" $release_file; then
    apt update >> $logfile 2>> $errorlog
    check_exit_status "apt update"
    
    apt dist-upgrade -y >> $logfile 2>> $errorlog
    check_exit_status "apt dist-upgrade"
    
    apt autoremove -y >> $logfile 2>> $errorlog
    check_exit_status "apt autoremove"
    
    apt autoclean >> $logfile 2>> $errorlog
    check_exit_status "apt autoclean"
    
    echo "$(date): Update completed successfully!" | tee -a $logfile
    
    # Optional: Check if reboot needed
    if [ -f /var/run/reboot-required ]; then
        echo "$(date): Reboot required for updates to take effect." | tee -a $logfile
    fi
else
    echo "This system is not Ubuntu or Debian-based. Exiting." | tee -a $logfile
    exit 0
fi