#!/bin/bash

##########################################################
# Backup and restore persistent log files
##########################################################

if [ ! -z "$1" ] && [ ! "$1" = "R" ]; then
	echo "Usage: $0 [R]"
	echo "R: restore files from backup."
	exit
fi

# kill previous process
##########################################################
thisproc=$(basename $0)
PID_FILE=/var/run/$thisproc.pid
# Read saved PID of previous instance.
read PID < "$PID_FILE"
kill -s 0 "$PID" &>/dev/null && kill -s 9 "$PID" &>/dev/null
# wait for process to exit.
sleep 2
# Save PID.
echo "$$" > "$PID_FILE"
##########################################################

BACKUP_INTERVAL=3600
FILES_STATUS_CHECK_INTERVAL=300
MIN_REC_COUNT=100
DO_RESTORE_FIRST=0

BACKUP_SRC_DIR="/mnt/bbram/"
BACKUP_DST_DIR="/mnt/bbram/backup/"
filesArray=("state/pending_events.db" "state/new_pending_events.db" "calldata/calldetail.log" "calldata/missedcalls.log" "calldata/badcalls.log" "calldata/conf/confdetail.log" "calldata/conf/calldetail.log" "calldata/conf/badcalls.log")
statusCheckExclusions=("state/new_pending_events.db")
valuesArray=(0 0 0 0 0 0 0 0)

##########################################################
# restore files at start-up
##########################################################
if [ "$1" = "R" ]; then
	DO_RESTORE_FIRST=1
fi

##########################################################
# get index in array by file name 
##########################################################
getindex()
{
value=$1
for (( i = 0; i < ${#filesArray[@]}; i++ )); do
    if [ "${filesArray[$i]}" = "${value}" ]; then
          echo $i;
    fi
done
}
##########################################################
# check if backup is needed
##########################################################
checkfile()
{
#	echo "checkfile:"$1 $2
	status=0

	if [ -z $1 ] || [ -z $2 ]; then
		return $status
	fi

	exclusion=$1
	for (( i = 0; i < ${#statusCheckExclusions[@]}; i++ )); do
		if [ "${statusCheckExclusions[$i]}" = "${exclusion}" ]; then
		return $status;
		fi
	done

	local totaladdedrecords=0
	stat /tmp/$1.count > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		return $status
	fi
	totaladdedrecords=$(/bin/cat /tmp/$1.count)
	local index=$(getindex $f)
	local v=${valuesArray[$index]}
	
#	/bin/logger -t $0 $totaladdedrecords" new records in file:"$1
	
	if [ $v -gt $totaladdedrecords ]; then 
		valuesArray[$index]=$totaladdedrecords
		v=$totaladdedrecords
		status=1
	fi

	local diff=$(($totaladdedrecords-$v))

	if [ $diff -ge $MIN_REC_COUNT ]; then 
		valuesArray[$index]=$totaladdedrecords
		status=1
	fi

#	echo "checkfile: return "$status
	
return $status
}

##########################################################
# copy file
##########################################################
copyfile()
{
#	echo "copyfile:"$1 $2

	if [ -z $1 ] || [ -z $2 ]; then
		return 1
	fi

#	/bin/logger -t $0 "copy file:"$1 $2

	/bin/cp -f $1 $2 > /dev/null 2>&1
	return $?
}
##########################################################
# restore file from backup
##########################################################
restorefile()
{
#	echo "restorefile:"$1 $2

	if [ -z $1 ] || [ -z $2 ]; then
		return 1
	fi

#	/bin/logger -t $0 "restore file:"$1 $2
	local lc=0
	lc=$(/bin/nbcat $2 | wc -l)

	if [ $lc -eq 0 ]; then
		/bin/cat $1 > $2
	fi

	return $?
}
##########################################################
# backup all files: if "force" argument is given: copy without checking
##########################################################
backupfiles()
{
#	echo "backupfiles if needed:"
#	/bin/logger -t $0 "backup files if needed ("$1")"

		for f in "${filesArray[@]}"
		do
			SRC_FILE=$BACKUP_SRC_DIR$f
			DST_FILE=$BACKUP_DST_DIR$f
			if [ "$1" = "force" ]; then
				copyfile $SRC_FILE $DST_FILE
			else
				checkfile $SRC_FILE $DST_FILE
				if [ $? -eq 1 ]; then
					copyfile $SRC_FILE $DST_FILE
				fi
			fi
		done
}
##########################################################
# restore all files
##########################################################
restorefiles()
{
#	echo "restorefiles:"
	for f in "${filesArray[@]}"
		do
			SRC_FILE=$BACKUP_DST_DIR$f
			DST_FILE=$BACKUP_SRC_DIR$f
			restorefile $SRC_FILE $DST_FILE
		done
}
##########################################################
# main processing
##########################################################
main()
{
	stat $BACKUP_SRC_DIR > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		echo "Error: Source directory does not exists."
		exit 1
	fi
	
	mkdir -p $BACKUP_DST_DIR/state/
	mkdir -p $BACKUP_DST_DIR/calldata/conf
	
	if [ $DO_RESTORE_FIRST -eq 1 ]; then
		restorefiles
	fi
	
	local C=0
	
	while true
	
	do

	TIME_DIFF=$(($BACKUP_INTERVAL-$C))
	if [ $TIME_DIFF -le 0 ]; then
		C=0
		backupfiles force
	else
		backupfiles check
	fi

	/bin/sleep $FILES_STATUS_CHECK_INTERVAL
	C=$(($C+$FILES_STATUS_CHECK_INTERVAL))

	done
}

#######################################################
# Main function
#######################################################

main

exit 0
