#!/bin/bash

# create a hardlinked backup
# this scripts figures out if the
# dump is incremental or full

prefix=/usr
exec_prefix=/usr
datadir=/usr/share/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() {
        echo "$PROGNAME DAYS BACKUPDIR NOW"
        echo
        echo "This is a small shell script that hard links directories"
        echo "It is the basis for rdup-simple"
        echo
        echo DAYS \ - look backup DAYS days for previous dumps
        echo BACKUPDIR \ - where to backup to
        echo NOW \ \ - Current date in YYYY/MM format
}

PROGNAME=$0
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
                dir=`$GNU_DATE +%Y%m/%d --date "$i days ago"`
                mon=`$GNU_DATE +%Y%m`
                if [[ -d $_BACKUPDIR/$dir ]]; then
                        # copy 'em over
                        _echo2 "Linking dir: \`$_BACKUPDIR/$dir'"
                        # create dir to be safe
                        mkdir -p $_BACKUPDIR/$mon
                        $GNU_CP -plr $_BACKUPDIR/$dir $_BACKUPDIR/$_NOW
                        return 0
                fi
        (( i++ ))
        done
        return 1
}

what $1 $2 $3
exit $?
