#!/bin/bash

version="0.1"

backup_path=none
backup_user=none
server=none
ssh_port=none
mail_config=none
mail=none

usage()
{
    echo "[-v] [-h] [-d directory] [-u user] [-s server] [-p port] [-a mail-config] [-m mail]"
}

version()
{
    echo "backup script: $version"
}

get_ops()
{
    while getopts duspam: opt; do
        case $opt in
            d) backup_path=$OPTARG ;;
            u) backup_user=$OPTARG ;;
            s) server=$OPTARG ;;
            p) ssh_port=$OPTARG ;;
            a) mail_config=$OPTARG ;;
            m) mail=$OPTARG ;;
            *) echo 'error in command line parsing' >&2
            exit 1
        esac
    done
}

get_ops $*

if [ "$backup_path" = "none" ]; then
    echo "missing backup path";
    exit 1
fi

if [ "$backup_user" = "none" ]; then
    echo "missing backup user";
    exit 1
fi

if [ "$server" = "none" ]; then
    echo "missing backup server address";
    exit 1
fi

if [ "$ssh_port" = "none" ]; then
    echo "missing backup server port";
    exit 1
fi

# make sure we are in the correct dir (locally)
cd $backup_path
mkdir -p backups
outfile="backups/backup_$(date +%Y_%m_%d).zip"

# result flags
success=true
failure_reason="Unknown."

# create backup
forgejo dump -c /etc/forgejo/app.ini -f $outfile

# check for success
if [ $? -ne 0 ]; then
    failure_reason="Failed to create forgejo backup."
    echo $failure_reason
    success=false
fi

# query size of output file
outfile_size=$(ls -l $outfile | cut -d ' ' -f5 | numfmt --to iec)
backup_dir_size=0

# copy backup to backup server
if [ "$success" = true ] ; then
    # check if ssh files are present (went missing in the past)
    if [[ -f ~/.ssh/id_rsa && -f ~/.ssh/id_rsa.pub ]]; then
        # simple scp to backup server
        scp -P $ssh_port $outfile $backup_user@$server:$backup_path
        scp_return=$?
        echo scp code $scp_return

        # check for success
        if [ $scp_return -eq 0 ]; then
            rm $outfile
            backup_dir_size=$(ssh -n $backup_user@$server -p $ssh_port "ls -l $backup_path" | awk '{sum += $5} END {print sum}' | numfmt --to iec)
            success=true
        else
            failure_reason="scp failed."
            success=false
        fi
    else
        failure_reason="Missing rsa file."
        echo $failure_reason
        success=false
    fi
fi

echo $success

if [ "$mail_config" != "none" ] && [ "$mail" != "none" ]; then
    # send info mail to configured mail address
    if [ "$success" = true ] ; then
        echo "reporting success"
        printf "Subject: Forgejo Backup - Success\n\nBackup ran successfully. Backup size: $outfile_size. Backup dir size: $backup_dir_size" | msmtp -a $mail_config $mail
    else
        echo "reporting failure"
        printf "Subject: Forgejo Backup - Failure\n\n$failure_reason" | msmtp -a $mail_config $mail
    fi
fi