#!/bin/bash

TITLE="Gentoo Auto Updater"
echo -e '\033]2;'$TITLE'\007'

HTML_FILE_LOCATION_AND_NAME=/var/www/localhost/htdocs/logs/latest_update.html

send_html() {
    local HTML_HEADER="<!DOCTYPE html><html><head><title>Latest Log at $(date)</title></head><body>"
    if [ $1 -eq 0 -a $2 -eq 0 ]; then
	echo -e "Result: Auto Update Successful at $(date)\n$(cat latest.auto_log)" > latest.auto_log
	echo -e "$HTML_HEADER<h1>Sync Status: <span style='color: green;'>Success</span></h1><br><h1>Emerge Status: <span style='color: green;'>Success</span></h1>" > $HTML_FILE_LOCATION_AND_NAME
    elif [ $1 -eq 0 ]; then
	echo -e "Subject: Auto Update Emerge Failed at $(date)\n$(cat latest.auto_log)" > latest.auto_log
	echo -e "$HTML_HEADER<h1>Sync Status: <span style='color: green;'>Success</span></h1><br><h1>Emerge Status: <span style='color: red;'>Failed</span></h1>" > $HTML_FILE_LOCATION_AND_NAME
    else
	echo -e "Subject: Auto Update Sync Failed at $(date)\n$(cat latest.auto_log)" > latest.auto_log
	echo -e "$HTML_HEADER<h1>Sync Status: <span style='color: red;'>Failed</span></h1><br><h1>Emerge Status: <span style='color: red;'>Failed</span></h1>" > $HTML_FILE_LOCATION_AND_NAME
    fi
    echo -e "<br><br><h2>Log Info</h2><br><p style='white-space: pre-wrap;'>" >> $HTML_FILE_LOCATION_AND_NAME
    cat latest.auto_log >> $HTML_FILE_LOCATION_AND_NAME
    echo -e "</p></body></html>" >> $HTML_FILE_LOCATION_AND_NAME
}

echo -e "\nUPDATER INFO: GENTOO AUTO UPDATER by Edox\n" > latest.auto_log
echo -e "\nUPDATER INFO: STARTING SYNC\n" >> latest.auto_log
echo -e '\033]2;'$TITLE': Syncing\007'

EMERGE_DEFAULT_OPTS="" emaint --auto sync | awk '/Action: sync for repo/ {print}' >> latest.auto_log
if [ $? -ne 0 ]; then
    echo 'ERROR: Failed to sync repos!' >> latest.auto_log
    send_html 1 1
    exit
fi

echo -e "\nUPDATER INFO: STARTING EMERGE\n" >> latest.auto_log
echo -e '\033]2;'$TITLE': Upgrading/Compiling\007'

tail -n 0 -f /var/log/emerge.log >> latest.auto_log &
TAIL_PROCESS=$!
EMERGE_DEFAULT_OPTS="" emerge --update --deep --quiet --with-bdeps=y @world
kill $TAIL_PROCESS
if [ $? -ne 0 ]; then
    echo 'ERROR: Packages failed to upgrade! Manual upgrading required!' >> latest.auto_log
    send_html 0 1
    exit
fi

echo -e '\033]2;'$TITLE': Finished\007'
send_html 0 0
exit
