#!/bin/sh
# Remote Auto Backup installation script	Version 1.00
#
# Copyright  2012 RTK Media, Inc.
# All Rights Reserved.
#
# Any unauthorized use, reproduction, transfer or disclosure is prohibited.
#
# name: RABInstall
#
# function: To install the Remote Auto Backup programs
#
# Author: Richard P Nolan - RTK Media, Inc.  (719) 522-0377 rich@rtkmedia.com
#
# inputs: 
#
# outputs: 
#
# history:                  	     	(spr#) 
# version  date      name		reason/description
# -------  --------  -----------------	--------------------------------------
# 1.00 	   09/25/12	 rpn	Original release
# ----------------------------------------------------------------------------
#

RABDIR="/versyss/rab"
RABTEMPDIR="$RABDIR/tmp"
CronDir="/usr/spool/cron/crontabs"
CronUser="root" ; CronUserID=0
TempFile="$RABTEMPDIR/RABCron$$"

Alldays="Every Day"     # What the user sees
Allday="*" # What we put in crontab
Mdays="Monday - Friday" # What the user sees 
Mday="1-5" # What we put in crontab
Tdays="Tuesday - Saturday" # What the user sees
Tday="2-6" # What we put in crontab
SAdays="Saturday & Sunday" # What the user sees
SAday="0,6" # What we put in crontab
SUdays="Sunday & Monday" # What the user sees
SUday="0,1" # What we put in crontab
# Days of week
SUNdays="Sunday Only" # What the user sees
SUNday="0" # What we put in crontab
MONdays="Monday Only" # What the user sees
MONday="1" # What we put in crontab
TUEdays="Tuesday Only" # What the user sees
TUEday="2" # What we put in crontab
WEDdays="Wednesday Only" # What the user sees
WEDday="3" # What we put in crontab
THUdays="Thursday Only" # What the user sees
THUday="4" # What we put in crontab
FRIdays="Friday Only" # What the user sees
FRIday="5" # What we put in crontab
SATdays="Saturday Only" # What the user sees
SATday="6" # What we put in crontab

#
# Begin Subroutines
#

FixPermiss()
{
  chmod 666 $1
  chown root $1
  chgrp system $1
}

GetRangeOfNumbers() # Input is Prompt, Low Range, High Range, Chars Valid Flag
{
Prompt=$1
LowRange=$2
HighRange=$3
AddValid=$4 # If we are going to allow A and a here
Valid=0 # Loop here until they give a valid entry
while [ $Valid -eq 0 ]
do
	echo "$Prompt \c"
  read Selection
      
  case $Selection in
    a*|A*)
			if [ $AddValid -eq 1 ]
		  then
				Valid=1
			fi ;;
    q*|Q*)     exit 0 ;;    # Wants to quit editing the crontab
		[0-9]*)    # If this is a number of some kind
		  if [ -z $Selection ] # If this is a zero length field
		  then
			  Valid=0 # Ensure they can't just press enter
      else
		    if [ $Selection -ge $LowRange -a $Selection -le $HighRange ]
		    then
			    Valid=1
        fi 
			fi ;;
	  *) Valid=0 ;;   # Ensure anything else is invalid as well
  esac

  if [ $Valid -eq 0 ] #If no valid character was entered
  then
    echo "enter a number between $LowRange and $HighRange"
  fi
done
}

Ask() # Input to routine is Default Answer then Prompt
{
DefaultAnswer=$1
Prompt=$2

echo "$Prompt\c"
read Answer
case $Answer in
  y|y*|Y|Y*|1) Answer=1 ;;  # Yes, Modify This Entry
  n|n*|N|N*|0) Answer=0 ;;  # No, Don't Modify This Entry
  a*|A*|2)     Answer=2 ;;  # Add an Entry
  q*|Q*|3)     exit 0 ;;    # Wants to quit editing the crontab
	*)           Answer=$DefaultAnswer ;; # Any invalids are just the default
esac
}

Clear()
{
tput clear
}

Home()
{
tput home
}

CronTab()
{
if [ -f ${CronDir}/${CronUser} ] # If we have crontab for root
then
  crontab -l 2>/dev/null | grep "${RABDIR}/rautobak" | grep -v "^#"
fi
}

ReadCron()
{
Sel=$1
Menu=0
CronTab | 
while [ $Menu -lt $Sel ]
do
  read Minute Hour Date Month Days Dummy
  Menu=`expr $Menu + 1`
  if [ $Menu -eq $Sel ]
  then
    [ "$Days" = "*" ] && Days="x*"
    Hour1=$Hour
	  Length=`expr "$Hour1" : ".*"`
    [ $Length -eq 1 ] && Hour1="0$Hour1"
    Minute1=$Minute
	  Length=`expr "$Minute1" : ".*"`
    [ $Length -eq 1 ] && Minute1="0$Minute1"
    echo "$Hour1 $Minute1 $Days"
  fi
done
}

ChangeCron() # Input Entry to fix, Min, Hour, Day, Change Mode "C" or "D"
{
Sel=$1
SetMinute=$2
SetHour=$3
SetDays="$4"
Flag=$5
Menu=0

if [ $Sel -ge 1 ]
then
  crontab -l 2>/dev/null | grep -v "$RABDIR/rautobak" >${TempFile}
  CronTab |
	while read Minute Hour Date Month Days Dummy
  do
    Menu=`expr $Menu + 1`
    if [ $Menu -eq $Sel ]
    then
	    [ $Flag = "D" ] && continue
      Minute=$SetMinute 
      Hour=$SetHour
	    Days="$SetDays"
    fi
    echo "$Minute $Hour $Date $Month $Days $Dummy" #Dummy is anything after Day
  done >> ${TempFile}
else
  crontab -l >${TempFile} 2>/dev/null
  echo "$SetMinute $SetHour * * $SetDays $RABDIR/rautobak >/dev/null 2>/dev/null" >>${TempFile} # Add a new Entry to the end of the file
fi

crontab ${TempFile}
rm ${TempFile}

}

WhatDay()
{
 case "$1" in
	"${Allday}")	echo "${Alldays}\c" ;;
	"${Mday}")	echo "${Mdays}\c" ;;
	"${Tday}")	echo "${Tdays}\c" ;;
	"${SAday}")	echo "${SAdays}\c" ;;
	"${SUday}")	echo "${SUdays}\c" ;;
	"${SUNday}")	echo "${SUNdays}\c" ;;
	"${MONday}")	echo "${MONdays}\c" ;;
	"${TUEday}")	echo "${TUEdays}\c" ;;
	"${WEDday}")	echo "${WEDdays}\c" ;;
	"${THUday}")	echo "${THUdays}\c" ;;
	"${FRIday}")	echo "${FRIdays}\c" ;;
	"${SATday}")	echo "${SATdays}\c" ;;
 esac
}

SetCron()
{
echo
Sel=$1

if [ $Sel -ge 1 ] # If we are modifying an entry, find it
then
  set `ReadCron $Sel` # Find the line in crontab for this entry
  Hour="$1" ; Minute="$2" ; Days="$3" ; [ "$Days" = "x*" ] && Days="*"
  Hour1="$Hour" ; Minute1="$Minute" ; Days1="$Days" # Remember What we read
else
  Hour=2 ; Minute=15 ; Days="*" #Just default to 2:15 am
  Hour1=0 ; Minute1=0 ; Days1="x" #Ensure they know we changed something
fi

GetRangeOfNumbers "Hour (0-23)   = " 0 23 0
Hour=$Selection
GetRangeOfNumbers "Minute (0-59) = " 0 59 0
Minute=$Selection

echo "
 Remember that a backup after midnight for Monday - Friday should be run
   Tuesday - Saturday.  What days do you want the backup to run?

1. ${Alldays}
2. ${Mdays}
3. ${Tdays}
4. ${SAdays}
5. ${SUdays}
6. ${SUNdays}
7. ${MONdays}
8. ${TUEdays}
9. ${WEDdays}
10. ${THUdays}
11. ${FRIdays}
12. ${SATdays}
"
GetRangeOfNumbers "Select : " 1 12 0
case $Selection in
  1) Days="${Allday}" ; Day=${Alldays} ;;
  2) Days="${Mday}" ; Day=${Mdays} ;;
  3) Days="${Tday}" ; Day=${Tdays} ;;
  4) Days="${SAday}" ; Day=${SAdays} ;;
  5) Days="${SUday}" ; Day=${SUdays} ;;
  6) Days="${SUNday}" ; Day=${SUNdays} ;;
  7) Days="${MONday}" ; Day=${MONdays} ;;
  8) Days="${TUEday}" ; Day=${TUEdays} ;;
  9) Days="${WEDday}" ; Day=${WEDdays} ;;
  10) Days="${THUday}" ; Day=${THUdays} ;;
  11) Days="${FRIday}" ; Day=${FRIdays} ;;
  12) Days="${SATday}" ; Day=${SATdays} ;;
  *) Days="$Days1" ; Day=`WhatDay "${Days}"` ;;
esac

Hour1=$Hour
Length=`expr "$Hour1" : ".*"`
[ $Length -eq 1 ] && Hour1="0$Hour1"
Minute1=$Minute
Length=`expr "$Minute1" : ".*"`
[ $Length -eq 1 ] && Minute1="0$Minute1"

Ask 1 "Set backup for ${Hour1}:${Minute1} ${Day}? [n,Y,q] " #default YES
if [ $Answer -eq 1 ]
then
  ChangeCron "$Sel" "$Minute" "$Hour" "$Days" C
fi
}

GraphOn()
{
echo "\016\c"
}

GraphOff()
{
echo "\017\c"
}
#
# End Subroutines
#

#
# The script file starts here
#

Status=1

if [ -x /usr/bin/id ]
 then
  eval `/usr/bin/id | sed 's/[^a-z0-9=].*//'`
  [ "${uid:=-1}" -eq $CronUserID ] && Status=0
 else
  [ ${LOGNAME:-zyxwv} = "${CronUser}" ] && Status=0
fi

if [ $Status -ne 0 ]
then
 echo "\nYou must be logged on as \"${CronUser}\" to change the backup time.\n"
 read junk
 exit 1
fi

#
# ensure the temporary directory is in the RABDIR directory
#
if [ ! -d ${RABTEMPDIR} ]  # See if we have the temporary RAB directory
then
  mkdir ${RABTEMPDIR} >/dev/null 2>&1
  FixPermiss ${RABTEMPDIR} >/dev/null 2>&1
fi
cd ${RABDIR}

# 
# Show the current status of entries for CronTab
#
while [ 1 -eq 1 ]
do
  Clear

  Count=`CronTab | wc -l`
  Count=`expr $Count + 0`

  if [ $Count -lt 1 ]
  then
    echo "\n\nCron is not set to do an Auto Backup"
  else
	  echo "The Current Date/Timestamp is `date`"
    echo "\nCron is set for :\n
     Time	Month	Date	Days
`GraphOn`zzzz      zzzzzz     zzz    zzzz                      `GraphOff`\n"

    Menu=0 # Initialize the counter
    CronTab |
		while read Minute Hour Date Month Day Command Dummy
    do
	    Length=`expr "$Hour" : ".*"`
      [ $Length -eq 1 ] && Hour="0$Hour" # Change 0-9 to 00-09
	    Length=`expr "$Minute" : ".*"`
      [ $Length -eq 1 ] && Minute="0$Minute" # Change 0-9 to 00-09
      [ "$Date" = "*" ] && Date=" All"
      [ "$Month" = "*" ] && Month=" All"

      Menu=`expr ${Menu} + 1`
      echo "${Menu}.  ${Hour}:${Minute}	${Month}	${Date}	`WhatDay \"${Day}\"`"
    done
  fi
  echo # Just put in a blank line
#
# End showing what we had before
#

  if [ $Count -le 1 ] # If we had no entries or only 1
  then
		if [ $Count -eq 1 ]
		then
		  Ask 0 "Modify this entry? [(N)o,(y)es,(q)uit,(a)dd] "
		else
		  Ask 1 "Set it now? [(n)o,(Y)es,(q)uit] "
			if [ $Answer -eq 0 ]
			then
				exit 0 # Cron isn't set for RAB and they don't want to
      fi
		fi
		if [ $Answer -eq 2 ] # If they chose to add
		then
			Answer=1 # Go on like we are going to modify
			Selection=0 # So we will be in add mode
		else
		  Selection=$Count # Which line we are going to edit
		fi
  fi
  
  if [ $Count -gt 1 ] # If we have more than one entry, select which one
  then
		GetRangeOfNumbers "Modify which entry (or (q)uit/(a)dd)? " 1 ${Count} 1
    Answer=1 # Yes, we want to modify the entry
		if [ "$Selection" -eq "a" ] || [ "$Selection" -eq "A" ]
		then # We are trying to add an entry, let's do that
			Selection=0 # This means we are going to add to crontab
    fi
  fi

	if [ $Count -eq 1 -a $Answer -eq 0 ]
	then
		continue # Only one entry and they don't want to edit or delete it
	fi

  if [ $Selection -ge 1 ] # If not adding, see if we should delete it
  then
	  Ask 0 "Delete this entry? [(N)o,(y)es,(q)uit] "
    if [ $Answer -eq 1 ] # If they said yes to deleting
    then
	    Ask 0 "Are you sure? [(N)o,(y)es,(q)uit] "
      if [ $Answer -eq 1 ] # If they answered Yes to this too
      then
        ChangeCron $Selection 0 0 0 D
      fi
      continue # Skip down to done
    fi
  fi
  case $Selection in
    [0-9]) SetCron $Selection ;; # Add or modify the entry in crontab
     *) exit 0 ;;  # Note, we just skip out if more than 9
  esac
done

echo

