#!/bin/bash

# create a hardlinked backup
# this scripts figures out if the
# dump is incremental or full. And makes a copy
# of the previous backup with GNU cp

prefix=/usr
datarootdir=${prefix}/share
exec_prefix=${prefix}
datadir=${datarootdir}/rdup
sysconfdir=/etc/rdup
GNU_DEFS=rdup-snapshot.gnu

# shared stuff
. $datadir/shared.sh
if [[ -r $sysconfdir/$GNU_DEFS ]]; then
        source $sysconfdir/$GNU_DEFS
fi
if [[ -z $GNU_DATE ]]; then
        GNU_DATE=date
fi
if [[ -z $GNU_CP ]] ;then
        GNU_CP=cp
fi

usage() {
	cat << HELP
$PROGNAME [-H] DAYS BACKUPDIR NOW

This is a small shell script that hard links directories
It is the basis for rdup-simple

-H	     include the hour in the backup directory

DAYS       - look backup DAYS days for previous dumps
	     with -H this calculates in hours
BACKUPDIR  - where to backup to
NOW        - Current date in YYYYMM format
             With -H, current date in YYYYMM/HH format
HELP
}

PROGNAME=$0
# parse our only option
getopts "H" hour;
if [[ $hour == "H" ]]; then
    hour=true;
    shift;
else
    hour=false
fi

if [[ $# -ne 3 ]]; then
        usage
        exit 2
fi

what() {
        _DAYS=$1
        _BACKUPDIR=$2
        _NOW=$3
        i=1
        if [[ -d $_BACKUPDIR/$_NOW ]]; then
                # already there do not link
                return 0
        fi
        # linux thing
        while [[ $i -le $_DAYS ]]; do
		if $hour; then
		    dir=`$GNU_DATE +%Y%m/%d/%H --date "$i hours ago"`
		    mon=`$GNU_DATE +%Y%m/%d`
		else
		    dir=`$GNU_DATE +%Y%m/%d --date "$i days ago"`
		    mon=`$GNU_DATE +%Y%m`
		fi
                if [[ -d $_BACKUPDIR/$dir ]]; then
                        # copy 'em over
                        _echo2 "Linking dir: \`$_BACKUPDIR/$dir'"
                        # create dir to be safe
                        if ! mkdir -p $_BACKUPDIR/$mon; then
			    return 2
			fi
			# it can be the case that we may also need to
			# create the directories leading up to $_NOW
			if ! mkdir -p $_BACKUPDIR/$(dirname $_NOW); then
			    return 2
			fi
                        if ! $GNU_CP -plr $_BACKUPDIR/$dir $_BACKUPDIR/$_NOW; then
			    return 2
			fi
                        return 0
                fi
        (( i++ ))
        done
        return 1
}

what $1 $2 $3
exit $?
