#!/bin/bash

export PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/sbin
logfile="/var/log/snapback.log"

# Function that takes an argument of number of seconds, and prints the time
# in the format HHh:MMm:SSs. You can use this to print e.g. runtime for a
# script.
# Usage: seconds_to_hms [SECONDS]
# If the argument is missing, or it is not an integer >0, 'NaN' is printed.
function seconds_to_hms() {
    local S_TIME HMS_TIME
    if [ -z "${1}" ]; then
        S_TIME="NaN"
    else
        S_TIME=${1}
    fi
    if [ ${S_TIME} -ge 0 ] 2> /dev/null; then
        HMS_TIME="$(printf '%02dh:%02dm:%02ds' $((S_TIME/3600)) $((S_TIME%3600/60)) $((S_TIME%60)))"
    else
        HMS_TIME="NaN"
    fi
    echo ${HMS_TIME}
}

# In case pre/post scripts don't exist, default value for their exit code
# variables is 0.
preexitcode=0
postexitcode=0

echo "$(date) Snapback started." >> ${logfile}
start=$(date +%s)

if [ -x "/usr/local/sbin/snapback.pre" ]; then
    echo "$(date) Pre-script starting." >> ${logfile}
    /usr/local/sbin/snapback.pre >> ${logfile} 2>&1
    preexitcode=${?}
    echo "$(date) Pre-script finished and returned with exit status ${preexitcode}." >> ${logfile}
fi

echo "$(date) Rdiff-backup started." >> ${logfile}
/usr/bin/rdiff-backup --server --restrict-read-only /
rdiffexitcode=${?}
echo "$(date) Rdiff-backup finished and returned with exit status ${rdiffexitcode}." >> ${logfile}

if [ -x "/usr/local/sbin/snapback.post" ]; then
    echo "$(date) Post-script starting." >> ${logfile}
    /usr/local/sbin/snapback.post >> ${logfile} 2>&1
    postexitcode=${?}
    echo "$(date) Post-script finished and returned with exit status ${postexitcode}." >> ${logfile}
fi

end=$(date +%s)
runtime=$((end-start))
echo "$(date) Snapback finished. Pre:${preexitcode}, Rdiff-backup:${rdiffexitcode}, Post:${postexitcode}. Duration: $(seconds_to_hms ${runtime}) (${runtime} seconds)." >> ${logfile}

# Exit with the sum of all exit codes from pre, rdiff-backup and post.
sumexitcode=$((preexitcode+rdiffexitcode+postexitcode))
exit ${sumexitcode}
