#!/bin/bash

### customizing section ###
SRCPATH=/usr/local/cgdb/arch
TAPEPATH=/usr/local/cgdb/tape
ARCHDELAY=3
OS=`uname`
###########################

LISTOPT=
MODE=

while getopts "m:t:f:p:o:b:" opt; do 
    case $opt in
	m)
	    MODE=${OPTARG}
	    ;;
	t)	    
	    TABLESET=${OPTARG}
	    ;;
	f)	    
	    ARCHFILE=${OPTARG}
	    ;; 
	p)
	    ARCHPATH=${OPTARG}
	    ;;
	o)
	    LISTOPT=${OPTARG}
	    ;;
	b)
	    BRANCH=${OPTARG}
	    ;;
	
	\?) 
	    echo "Invalid option: -$OPTARG" >&2 
	    ;; 
	:) 
	    echo "Option -$OPTARG requires an argument." >&2 
	    exit 1 
	    ;; 
    esac 
done


if [ "$MODE" = "list" ]
then
    if [ "$LISTOPT" = "numarchived" ]
    then
	numArchived=0
	if [ "$ARCHPATH" = "$SRCPATH" ]
	then
	    for f in `ls $TAPEPATH/$TABLESET-$BRANCH-* 2>/dev/null`
	    do
		# echo Found $f
		(( numArchived++ )) #=numArchied+1))
	    done
	fi
	echo $numArchived
	exit 0
    else
	echo "Unknown list option"
	exit 1
    fi
elif [ "$MODE" = "archive" ]
then
    for f in `ls $SRCPATH/$TABLESET-* 2>/dev/null`
    do

	# linux

	if [ "$OS" == "FreeBSD" ] \
	       || [ "$OS" == "Darwin" ]
	then
	    # osx / freebsd
	    fileTS=`stat -f %c -t %s $f`
	elif [ "$OS" == "Linux" ]
	then
	    # linux
	    fileTS=`stat --printf=%W $f`
	else
	    echo "Unknown OS"
	    exit 1
	fi

	currTS=`date +%s`
        (( secDiff = currTS - fileTS ))
	if (( $secDiff > 60*60*$ARCHDELAY ))
	then
	   echo "Archiving file $f with secdiff $secDiff"
	   mv $f $TAPEPATH
           bf=`basename $f`
           gzip $TAPEPATH/$bf
	fi
    done
elif [ "$MODE" = "recover" ]
then
    pathFound=no
    IFS=":"
    for path in $ARCHPATH
    do
	if [ $path = $SRCPATH ]
	then
	    pathFound=yes
	fi
    done
    
    if [ $pathFound = "yes" ]
    then
	for i in 1 2 3 
	do
	    if [ -e "${TAPEPATH}/${ARCHFILE}.gz" ]
	    then
		# TARGETPATH=`echo $ARCHPATH | awk -F: '{ print $1 }'`
		
		echo "Restoring $ARCHFILE ..."
		cp ${TAPEPATH}/${ARCHFILE}.gz $SRCPATH
		if [ $? -eq 0 ]
		then
                    gunzip ${SRCPATH}/${ARCHFILE}.gz
		    exit 0
		else
		    # errorcode > 1 indicates any problem 
		    exit 2
		fi
	    fi
	    sleep 1
	done
    else
	echo "Source path $SRCPATH not found in arch path $ARCHPATH"
	exit 2
    fi
    
    # errorcode = 1 indicates no further log files available 
    exit 1
    
else
    echo "Unknown mode"
    exit 1
fi
