#! /bin/bash

###############################################################################
#
# fupdate: The File Updater - last updated 03Jan01
#
# by:	Brad Doster
#	Insight Network Solutions
#	www.InsightNetSolutions.net
#	bdoster@home.com
#
# Copyright (c) Brad Doster, 2001
#
# Distribution limits:
#
#	1) Give this file (fupdate) away to whomever you want, as long as:
#		a) The content of this file is unmodified in any way.
#		b) It's FREE -- no distribution is permitted for exchange or 
#		   trade of anything.
#	2) Exceptions to 1) require prior written consent from the author and
#	   the copyright holder.
#
# Warranty info:
#
#	There is no warranty whatsoever that this script does what it says it
#	does, or does anything else.  If you choose to use it, it is entirely
#	at your own risk.
#
#------------------------------------------------------------------------------
#
# README
#
# This script installs updated files located in a directory referred to as the
# Edit Directory.  By default, this directory is named '_edit_', but it is
# easily altered by changing the 'ed=_edit_' line below.  The purpose of the
# script is to provide a semblance of organization in preserving old files when
# replacing them with newer, updated versions.
#
# The Edit Directory should be placed below the directory containing the
# file(s) to be updated.  The new files should then be placed in the Edit
# Directory and modified there as needed.  For example, if you wanted to modify
# your /etc/rc.d/rc.local file, you would:
#
#       mkdir /etc/rc.d/_edit_
#       cp /etc/rc.d/rc.local /etc/rc.d/_edit_
#       Edit the copy of rc.local in the Edit Directory.
#       Execute this script (fupdate) and select rc.local as a file to update.
#
# The script steps are as follows:
#
#       Make sure the current directory is the Edit Directory -- if not, exit.
#       Allow the user to select one or more files to be updated.  Once files
#       are selected and the option to perform the update is chosen...
#       Extract the current date and time in the form YYMMDD-HHMMSS, to be used
#	in preserving the original file(s) by renaming it(them) to
#	'filename-YYMMDD-HHMMSS'.
#	Check that the intended backup filenames don't exist -- if they do,
#	prompt the user re: what to do.
#	Check that there are original files to be renamed -- if not, prompt the
#	user re: what to do.
#	Attempt to rename the original file(s) from 'filename' to
#	'filename-YYMMDD-HHMMSS' -- if unsuccessful, display an error and exit.
#	Attempt to copy the updated file(s) from '_edit_' to '..' -- if
#	unsuccessful, display an error and exit.
#       Mark the newly installed files as read-only.
#       List the new and the old files in long format for review.
#
# At several places in the script, a menu of items may be displayed.  Menu
# items may be selected by number, or in cases where (char) appears in the
# menu item text, the upper or lower case 'char' may be used to choose the
# item.  For example, if the following menu item is shown...
#
#	3) Select-(A)ll-Files
#
# ...'3', 'a' or 'A' may be used to select the menu item.
#
###############################################################################

#------------------------------------------------------------------------------
# Function Definitions

# Cleanup
cleanup() {

	# Arguments: $varlist "custom message"
	for vname in "$1"; do
                unset $vname
        done
        unset vname
	unset varlist
	if [ ! "$2" = "" ]; then
		clear
		echo "** fupdate message: $2"
		echo
	fi
}

err_cant_ren() {

	# Arguments: $pd $fname $fname_ext
	clear
	echo "** fupdate error: can't rename file"
	echo
	echo "fupdate was unable to rename $1$2 to"
	echo "$1$2$3."
	echo
	echo "Please verify that you have the rights needed to rename"
	echo "$1$2, then try again."
	echo

}

err_cant_copy() {

	# Arguments: $pd $wd $fname 
	clear
	echo "** fupdate error: can't copy file"
	echo
	echo "fupdate was unable to copy $1$2/$3 to"
	echo "$1$3."
	echo
	echo "The problem may be any of the following:"
	echo
	echo "  Not enough disk space"
	echo "  You don't have the rights needed to create files in $1"
	# The possibility of a read-only file might be mentioned, however if the
	# file rename executed prior to this had failed, we would not have made
	# it this far in the script.
	# The possibility of the source file not existing could be mentioned 
	# here, however the file was selected from a dynamically generated list
	# of files in the Edit (source) Directory, so if the source file doesn't
	# exist, there's something else terribly wrong with this script.
	echo
	echo "Please investigate, repair the problem, then try again."
	echo

}

#------------------------------------------------------------------------------
# The Script

# Define the name of the Edit Directory
#
# Note: The name of the Edit Directory should be something unique which does
# does not appear elsewhere in your directory structure (other than for
# additional Edit Directories for use by this script).  If you choose a name
# common to your directory structure, this script may break with unpredictable
# results.  For example, if your Edit Directory is named 'edit' and is placed
# below a directory named 'myedits', calculation of the parent directory (pd)
# variable will fail, wreaking all kinds of havoc that this script writer
# doesn't want to deal with.
#
# If you've read the above note, change the following line to change the name
# of the Edit Directory this script looks for:
ed=_edit_
varlist=ed

# Get the current Working Directory -- if it's not '$ed' then print a 
# message and exit.
wd=`pwd | awk -F "/" '{ print $NF }'`
varlist="$varlist"' wd'

if [ ! "$wd" = "$ed" ]; then
	clear
	echo "** fupdate error: wrong directory"
        echo
        echo "Please change to the '$ed' directory before executing this script."
        echo
	echo "To change the name of the Edit Directory this script looks for,"
	echo "change the following script line to suit your preference:"
	echo
	echo "ed=_edit_"
	echo
	cleanup "$varlist"
        exit
fi

# Get the Parent Directory name
pd=`pwd | sed -e 's/'$ed'//' | awk '{ print }'`
varlist="$varlist"' pd'

# Build the menu
choice1a="[No files selected]"
choice1b="(G)o - Do the update"
choice1=$choice1a
choice2="(Q)uit - No update"
choice3a="Select (A)ll Files"
choice3b="[All Files Selected]"
choice3=$choice3a
choice4="(C)lear Selection "

uplist=
REPLY=
varlist="$varlist"' choice1a choice1b choice1 choice2 choice3a choice3b choice3'
varlist="$varlist"' choice4 uplist REPLY'

# Select the file(s) to update -- repeat this loop forever (until Go or Quit is
# selected from the menu)
doit=yes
varlist="$varlist"' doit fname'

while [ -n "$doit" ]; do
	# The menu is presented at the end of loop because... I don't recall,
	# but the logic worked out that way.  Therefore, don't do the stuff at
	# the top of the loop in the first pass...
	if [ -n "$REPLY" ]; then
		# Examine the menu selection and build the update list ($uplist)
		case "$REPLY" in
			1|G|g)
				case "$REPLY" in
					G|g)
						# If letters are used to make
						# menu choices, then fname is
						# not set, so set it here...
						fname=$choice1
						;;
				esac

				if [ "$fname" = "$choice1b" ]; then
					# Item 1) was chosen before any files
					# were selected, so try again...
					break
				fi
				fname=
				;;
			2|Q|q|:Q|:q)
				# Time to quit...
				cleanup "$varlist" "User quit without updating"
				exit
				;;
			3|A|a)
				# All files were selected...
				uplist=*
				choice1=$choice1b
				choice3=$choice3b
				fname=
				;;
			4|C|c)
				# Clear the selected files and try again...
				uplist=
				choice1=$choice1a
				choice3=$choice3a
				fname=
				;;
		esac

		if [ -n "$fname" ]; then
			# I wanted to use a 'case' statement here, but could
			# not get variables to work as test values.
			if [ "$fname" = "$choice1a" -o "$fname" = "$choice1b" \
			-o "$fname" = "$choice2" -o "$fname" = "$choice3a" \
			-o "$fname" = "$choice3b" -o "$fname" = "$choice4" ]; 
			then
				# Weird... something like '2^Hxxx' was pressed,
				# in which case '2' is NOT in $REPLY, but (in
				# this example), '(Q)uit--No-update' IS in 
				# $fname.  I could have checked for '2*' in 
				# the 'case' statement, but '20' (a possibly
				# valid choice) would have been treated as '2'.
				# So, clean up 'fname' and move on...
				fname=
			else
				# Update the update list...
				choice1=$choice1b
				choice3=$choice3a
				cklist=`echo $uplist | grep -w $fname`
				if [ -z "$cklist" ]; then
					uplist=$uplist' '$fname
				fi
			fi
		fi
	fi

	# Prepare the screen for the menu display
	clear

	if [ -z "$uplist" ] ; then
        	echo "Select the files to update from $pd$ed/ to $pd:"
		echo
	else
                echo "Select additional files, or select option 1) to update the following files:"
                echo
                echo $uplist
                echo
	fi

	# Present the menu
        select fname in "$choice1" "$choice2" "$choice3" "$choice4" *; do
		# I really don't know what should go here.  For reasons I don't
		# recall right now, the logic seemed to work better when
		# processed above rather than here.  In any event, this works!
		return
        done
done

# Build the filename extension for files to be backed up (-YYMMDD-HHMMSS)
currdate=`date +%y%m%d | awk '{ print }'`

currtime=`date +%H%M%S | awk '{ print }'`

fname_ext='-'"$currdate"'-'"$currtime"

# Process the selections

# The '. ' at the beginning and ' .' at the end of the following variables
# allows them to be searched with sed for whole words, e.g. search for ' word '
renfiles='. '$uplist' .'
cpyfiles='. '$uplist' .'

choice=
varlist="$varlist"' currdate currtime fname_ext renfiles cpyfiles'
varlist="$varlist"' choice choices'

for fname in $uplist ; do
        # Make sure the destination backup files don't already exist
        if [ -f ../$fname$fname_ext ]; then
		clear
		echo "** fupdate warning: backup file already exists"
		echo
		echo "A file named '$fname$fname_ext' already exists in $pd."
		echo
		echo "If you answer Yes below, the existing backup file will be overwritten!"
		echo
		echo "Do you wish to continue and overwrite the existing file"
		echo "$pd$fname$fname_ext?"
		echo
		echo 'Type '\'Y\'' (case sensitive!) and press Enter to overwrite.  Any other response'
		echo "means No:"
		echo
		choice1="Yes    - Overwrite '$pd$fname$fname_ext'"
		choice2="No     - Do not overwrite '$pd$fname$fname_ext'"
		choice3="(Q)uit - No updates will be performed"
		select choice in "$choice1" "$choice2" "$choice3"; do
			return
		done
		case "$REPLY" in
			3|Q|q|:Q|:q)
				cleanup "$varlist" "User quit at file overwrite prompt"
				exit
				;;
		esac
		if [ ! "$REPLY" = "Y" ]; then
			# Selection was No, so remove fname from the list of
			# files to be renamed and copied
			cpyfiles=`echo $cpyfiles | sed "s/ $fname / /"`
			renfiles=`echo $renfiles | sed "s/ $fname / /"`
			echo
			echo "'$fname' has been removed from the list of files to be updated."
			sleep 3
		else
			# User is choosing to overwrite a file -- let's be sure
			# about this!
			echo
			echo "$pd$fname$fname_ext will be overwritten."
			echo "Type 'Y' and press Enter again to confirm."
			echo
			select choice in "$choice1" "$choice2" "$choice3"; do
				return
			done
			case "$REPLY" in
				3|Q|q|:Q|:q)
					cleanup "$varlist" "User quit at file overwrite prompt"
					exit
					;;
			esac
	                if [ ! "$REPLY" = "Y" ]; then
				# User is fickle, or made a typo above --
				# remove fname from lists...
	                        cpyfiles=`echo $cpyfiles | sed "s/ $fname / /"`
        	                renfiles=`echo $renfiles | sed "s/ $fname / /"`
                        	echo
	                        echo "'$fname' has been removed from the list of file to be updated."
				# Is there a way to say "Press any key to
				# continue"?  If so, I can't find it, so we
				# sleep a bit instead...
        	                sleep 3
			fi
		fi
        fi
done

if [ ! "$renfiles" = ". ." ]; then
	# Make sure the source files to be renamed do exist
	for fname in $renfiles; do
		if [ ! "$fname" = "." ]; then
			if [ ! -f ../$fname ]; then
				clear
				echo "** fupdate message: original file does not exist"
				echo
				echo "$pd$fname does not exist, so there's nothing to backup."
				echo
				echo "Do you still want to copy '$fname' from $pd$wd/ to"
				echo "$pd?"
				echo
				choice1="(Y)es  - Copy '$pd$wd/$fname' to '$pd'"
				choice2="(N)o   - Do not copy '$pd$wd/$fname' to '$pd'"
				choice3="(Q)uit - No updates will be performed"
				select choice in "$choice1" "$choice2" \
				"$choice3"; do
					return
				done
				case "$REPLY" in
					3|Q|q|:Q|:q)
						cleanup "$varlist" \
						"User quit at file copy prompt"
						exit
						;;
					2|N|n)
						# User chose to remove fname
						# from the list of files to be
						# copied...
						cpyfiles=`echo $cpyfiles | \
						sed "s/ $fname / /"`
						;;
				esac
				# Since $pd$fname doesn't exist, remove it from
				# the list of files to be renamed
				renfiles=`echo $renfiles | sed "s/ $fname / /"`
			fi
		fi
	done

	# Rename the existing files to be replaced
	varlist="$varlist"' rc'
	for fname in $renfiles ; do
		if [ ! "$fname" = "." ]; then
			# Rename with force since we've already requested
			# double confirmation for overwrites
			mv -f ../$fname ../$fname$fname_ext
			rc=$?
			# Check for success
			if [ ! -f ../$fname$fname_ext -o $rc -gt 0 ]; then
				# Oops!  The rename failed!
				err_cant_ren $pd $fname $fname_ext
				cleanup "$varlist"
				exit
			fi
		fi
	done
fi

#Copy the updated files from the Edit Directory to its parent directory
clear
if [ "$cpyfiles" = ". ." ]; then
	echo "** fupdate message: no files copied"
	echo
	echo "No files were selected to be copied from $pd$wd/ to"
	echo "$pd."
else
	echo "Your newly installed files in $pd are:"
	echo
	for fname in $cpyfiles; do
		if [ ! "$fname" = "." ]; then
			# Do the copy without force as destination files with
			# the same name should have been renamed already or we
			# would not be here
			cp -p $fname ..
			rc=$?
			# Check the result
        		if [ ! -f ../$fname -o $rc -gt 0 ]; then
                		err_cant_copy $pd $wd $fname
	                	cleanup "$varlist"
	        	        exit
		        else
				# Success, so set the file to read-only
				chmod -w ../$fname
				cd ..
				# List the updated file(s)
				ls -l $fname
				cd $ed
			fi
		fi
	done
fi

echo
if [ "$renfiles" = ". ." ]; then
	echo "** fupdate message: no files backed up"
	echo
	echo "There were no files selected to be backed up (renamed) in $pd."
else
	# List the files that were backed up
	cd ..
	echo "Your backed up files in $pd are:"
	echo
	for fname in $renfiles ; do
		if [ ! "$fname" = "." ]; then
			ls -l $fname$fname_ext
		fi
	done
	cd $ed
fi
echo
echo

# We're done, so clean up and get outta here!
cleanup "$varlist"

