#!/bin/bash

# Clear the terminal for cleanliness
clear

# Function to handle errors
handle_error() {
    echo "Error occurred while executing: $1"
    exit 1
}

# Function to add the cron job
add_cron_job() {
    # Define the cron job
    cron_job="0 9 * * 6 /root/os-update.sh"

    # Check if the cron job already exists
    (crontab -l 2>/dev/null | grep -qF "$cron_job") || {
        # If not, add it to the crontab
        (crontab -l 2>/dev/null; echo "$cron_job") | crontab - || {
            echo "Failed to add the cron job."
            exit 1
        }
        echo "Cron job added successfully: '$cron_job'"
    }
}

echo "============================================"
echo "       Automatic System Maintenance         "
echo "============================================"

# Get updates
echo "Step 1: Getting Updates..."
echo "--------------------------------------------"
sleep 1
DEBIAN_FRONTEND=noninteractive apt-get update -qq || handle_error "apt-get update"

echo "________________________________________________"
sleep 1

# Installing updates
echo "Step 2: Installing Updates..."
echo "--------------------------------------------"
sleep 1
DEBIAN_FRONTEND=noninteractive apt-get dist-upgrade -y -q || handle_error "apt-get dist-upgrade"

echo "________________________________________________"
sleep 1

# Auto remove unnecessary packages
echo "Step 3: Auto Removing Unused Packages..."
echo "--------------------------------------------"
sleep 1
DEBIAN_FRONTEND=noninteractive apt-get autoremove -y -q || handle_error "apt-get autoremove"

echo "________________________________________________"
sleep 1

# Clean up old package files
echo "Step 4: Cleaning Up Unused Package Files..."
echo "--------------------------------------------"
sleep 1
DEBIAN_FRONTEND=noninteractive apt-get clean -q || handle_error "apt-get clean"
DEBIAN_FRONTEND=noninteractive apt-get autoclean -y -q || handle_error "apt-get autoclean"

echo "________________________________________________"
sleep 1

# Add Cron Job before reboot
add_cron_job

# Prepare for reboot
clear
echo "============================================"
echo "           System Maintenance Complete      "
echo "============================================"
echo "System will REBOOT in 30 seconds..."
sleep 30

# Reboot the system
reboot