#!/bin/bash
# -*- mode: sh; fill-column: 75; tab-width: 8; coding: utf-8-unix -*-
# https://lukas.dzunko.sk/index.php/Linux:_incremental_backup_using_rsync_on_btrfs_with_snapshots

PREFIX=/var/local
ROLE=testforge

MONIKER=4TA
DEST=/mnt/backup
snapshot=""
opt=""

usage() {
    echo "Usage: $0 [OPTIONS] dirs"
    echo
    echo " -s | --snapshot               - snapshot"
    echo " -c | --checksum               - checksum"
    echo " -p | --dedupe                 - dedupe"
    echo " -d | --dest                   - destination (default - $DEST )"
    echo
    echo " -V | --version                - print version of this script"
    echo " -h | --help                   - print this help"
}

[ "$#" -eq 0 ] && usage && exit  1

SHORTOPTS="hVcspm:d:"
LONGOPTS="help,version,checksum,snapshot,dedupe,moniker:,dest:"
dedupe=
DIRS=

. /usr/local/bin/usr_local_base.bash || exit 2
error () { retval=$1 ; shift; echo "ERROR: $prog" $* ; exit $retval ; }

ARGS=$(getopt --options $SHORTOPTS  --longoptions $LONGOPTS -- "$@")
[ $? != 0 ] && error 2 "Aborting."

eval set -- "$ARGS"

while true; do
#    echo $*
    case "$1" in
        -p|--dedupe)
	    dedupe="true"
            ;;
        -s|--snapshot)
	    snapshot="true"
            ;;
        -c|--checksum)
            opt="--checksum"
            ;;
        -m|--moniker)
            shift
            MONIKER="$1"
            ;;
        -d|--dest)
            shift
            DEST="$1"
            ;;
        -v|--verbosity)
            shift
            verbosity="$1"
            ;;
        -V|--version)
            usage
            exit 0
            ;;
        -h|--help)
            usage
            exit 0
            ;;
        '--')
            shift
            DIRS="$@"
            break
            ;;
        *)
	    error 3 "unrecognized arguments $*"
            break
            ;;
    esac
    shift
done

[ -z  "$DIRS" ] && error 4 "no directories given"

df | grep ${DEST}  || mount -v ${DEST} || exit 3

echo "INFO: Copying data ..."
# output of following commands is saved along with backup
(  echo; echo "lsusb:" ; lsusb;
   echo; echo "lspci:"; lspci;
   echo; echo "lshw:"  ; lshw -short;
   echo; echo "date:"  ; date;
   echo; echo "# EOF"  ;
) > /.lastbackup_$MONIKER
echo

shopt -s nullglob

[ -d /var/local/etc/testforge/backup ] || mkdir /var/local/etc/testforge/backup
file=/var/local/etc/testforge/backup/$MONIKER.exclude
if ! [ -f $file ] ; then
    cat > $file << EOF
/cdrom
/dev
/media
/mnt
/proc
/run
/sys
/tmp
EOF
    for elt in /root/.cache /home/*/.cache ; do
	 grep -q ^$elt $file || echo $eelt >> $file
       done
  fi

LARGS="${opt} -vaxHAX --delete --delete-excluded --human-readable --stats --exclude-from=$file"
for dir in $DIRS ; do
    [ -d $dir ] || continue
    # copy data to backup location
    dest=$( echo $dir | sed -e 's@/mnt/@@' )
    rsync $LARGS\
	  ${DEST}/${MONIKER}/$dest || { retval=$? ; ERROR backing up $dir ; sync; exit $retval ; }
  done

echo "Flushing file system buffers ..."
time sync
btrfs filesystem sync ${DEST}
time sync
echo

if [ $dedupe = "true" ] ; then
    echo "INFO: deduping backup ..."
    time $PREFIX/bin/testforge_ln_dups.perl ${DEST}/${MONIKER}
fi

if [ $snapshot = "true" ] ; then
    echo "INFO: Creating snapshot of backup ..."
    btrfs sub snap -r ${DEST}/${MONIKER} "${DEST}/${MONIKER}_$(LANG=C date +%Y-%m-%d_%s)" || exit 4
fi

echo "INFO: Umounting backup filesystem ..."
umount -v ${DEST} || exit 6
echo

exit 0

