#!/bin/sh

set -ex

check_status() {
    local status_code=$1
    local msg="${2:-task}"

    if [ "$status_code" -ne "0" ]; then
        echo "ERROR: $msg failed, exit status was $status_code"
        exit "$status_code"
    else
        echo "OK: $msg succeeded"
    fi
}

populate_directory() {
    local target="$1"
    local tempfile

    # target must exist and be a directory
    test -d "$target" || exit 1

    for n in $(seq 1 10); do
        tempfile=$(mktemp "$target/tmp.XXXXXX")
        # the date command makes each tempfile different
        # the seq command just produces a lot of output
        # using a "here" document as to not pollute the set -x
        # output with large command lines
        cat > "$tempfile" <<EOF
$(date +%s%N)
$(seq 1 81920)
EOF
    chmod 0644 "$tempfile"
    done
}

add_samba_share() {
    if ! testparm -s 2>&1 | grep -qE "^\[public\]"; then
        echo "Adding [public] share"
        cat >> /etc/samba/smb.conf <<EOFEOF
[public]
  path = /public
  read only = no
  guest ok = yes
EOFEOF
        service smbd reload
    else
        echo "No need to add [public] share, continuing."
    fi
    echo "Populating share"
    rm -rf /public
    mkdir -p /public
    chmod 1777 /public
    populate_directory /public
}

add_localhost_backuppc_config() {
    cat > /etc/backuppc/localhost.pl <<EOFEOF
\$Conf{XferMethod} = 'smb';
\$Conf{XferLogLevel} = 1;
\$Conf{ClientCharset} = '';
\$Conf{ClientCharsetLegacy} = 'iso-8859-1';
\$Conf{SmbShareName} = 'public';
\$Conf{SmbShareUserName} = '';
\$Conf{SmbSharePasswd} = '';
\$Conf{PingPath} = '/bin/ping';
\$Conf{Ping6Path} = '/bin/ping6';
EOFEOF
}

echo "Adding samba share"
add_samba_share

echo "Configuring backuppc"
add_localhost_backuppc_config

result=0
echo "Performing a full backup"
sudo -u backuppc -H /usr/share/backuppc/bin/BackupPC_dump -v -f localhost || result=$?
check_status $result "Full backup"

result=0
echo "Changing share content and performing an incremental backup"
populate_directory /public
sudo -u backuppc -H /usr/share/backuppc/bin/BackupPC_dump -v -i localhost || result=$?
check_status $result "Incremental backup"

echo "Done."
