#!/bin/bash

### customizing section ###
SRCPATH=./arch
TAPEPATH=./tape
###########################

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
    elif [ "$LISTOPT" = "XXX" ]
    then
	echo "XXX"
	exit 0
    else
	echo "Unknown list option"
	exit 1
    fi
elif [ "$MODE" = "archive" ]
then
    for f in `ls $SRCPATH/$TABLESET-* 2>/dev/null`
    do
	echo "Arching file $f ..."
	mv $f $TAPEPATH
    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" ]
	    then
		# TARGETPATH=`echo $ARCHPATH | awk -F: '{ print $1 }'`
		
		echo "Restoring $ARCHFILE ..."
		cp $TAPEPATH/$ARCHFILE $SRCPATH
		if [ $? -eq 0 ]
		then
		    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
