#!/bin/bash
#
# __copy1__
# __copy2__
#
CMD=$(basename $0)
CMDVER="1.2"
CMDSTR="$CMD v$CMDSTR (2020/02)"

datematch="20[0-9][0-9][0-9][0-9][0-9][0-9]"

set -u

usage()
{
	echo "
=== $CMDSTR === SHOW CHANGES BETWEEN THE LAST 2 kusa INVOCATIONS ===

usage: $CMD command [date]

commands:
  l list	list changes dates and file counts (date ignored)
  f files	list changed files for date
  d diff	show diff in changed files
  p pdiff	show diff in changed files (patch format)

date in the form [YYYY]MMDD (default last date is $lastdate)
" >&2
	exit 1
}



listfiles()
{
	local date=$1

	bckfiles=$(find $backupdir -name "*.$date")
	[ "$bckfiles" == "" ] && {
		echo -e "\nno changes made on $date, try another date\n"
		exit 1
	}
	echo "$bckfiles" | sed -e "s#$backupdir##" -e "s/\.$date//"
}





# (MAIN)

[ "$(id -u)" != 0 ] && {
	echo "you need to be root for this command" >&2
	exit 1
}

backupdir="/etc/backup"
files=$(ls $backupdir/etc/motd.*.$datematch $backupdir/etc/motd.$datematch 2>/dev/null)
lastdate=$(echo "$files" | sed -e "s/.*\.//" | sort | tail -1)
lastdate=${lastdate:-NONE}


[ $# -lt 1 ] && usage
mode=$1; shift

case $mode in
  l|list)	mode="l" ;;
  f|files)	mode="f" ;;
  d|diff)	mode="d" ;;
  p|pdiff)	mode="p" ;;
  *)		usage ;;
esac

case ${1:-""} in
  "")			;;
  [0-9][0-9][0-9][0-9])	lastdate="$(date +%Y)$1" ;;
  $datematch)		lastdate=$1 ;;
  *)			usage ;;
esac

[ "$lastdate" == "NONE" ] && {
	echo -e "\nno changes (kusa-conf never ran?)\n"
	exit 1
}

if [ $mode == "l" ]
then
	dates=$(echo "$files" | sed -e "s/.*\.//" | sort -r)
	cols=$(tput cols)
	cols=$(expr $cols - 15)


	echo "DATE      CNT FILE(s)"

	for dt in $dates
	do
		bckfiles=$(listfiles $dt)
		count=$(echo "$bckfiles" | wc -l)
		bckfiles=$(echo $bckfiles)

		printf "%s %4d %-${cols}.${cols}s\n" $dt $count "$bckfiles"
	done
	exit 0
fi


echo -e "\nCHANGED FILES ON $lastdate\n"


# mode: files
#
[ $mode == "f" ] && {
	listfiles $lastdate
	exit 0
}

# mode: diff
#
IFS=$'\n'
for file in $(listfiles $lastdate)
do
	if [ -f "$file" ]
	then
		if [ "$mode" == "p" ]
		then
			diff -u "$file" "$backupdir$file.$lastdate"
		else
			echo
			echo "=== < ACTUAL === > PREVIOUS_VERSION ==="
			echo "=== < $file === > $backupdir$file.$lastdate ==="
			echo 
			diff "$file" "$backupdir$file.$lastdate"
		fi
	else
		echo -e "\n\n=== $file no longer exists (deleted)\n"
	fi
done

exit 0
