#!/bin/bash

function printHelp()
{
	echo "hsdiff - compares files with file version on master host"
	echo 
	echo "syntax: hsdiff [--master <master account>] [OPTIONS] [FILELIST]"
	echo "sample: hsdiff -q '*'"
	echo
	echo "Takes all single OPTIONS from GNU diff."
	echo "Compares each file from FILELIST with same file on master host."
	echo "Accesses master host by ${MASTER_ACCOUNT}."
	echo "Cannot deal with directories yet."
}

# include the configuration file
source /root/etc/config || {
	echo "ERROR: Cannot source /root/etc/config." >&2
	exit 1
}

# get opts
aOpts=""
while [ "${1:0:1}" = "-" ]; do
	case "$1" in
		-h|--help) printHelp; exit;;
		-m|--master) MASTER_ACCOUNT="$2"; shift 2;;
		*) aOpts="$aOpts $1"; shift;;
	esac
done

# help?
if [ -z "$*" ]; then
	printHelp
	exit
fi

# create a temp directory
aTemp=`mktemp`
if [ -z "$aTemp" -o "${aTemp:0:5}" != "/tmp/" -o ! -f "$aTemp" ]; then
	echo "ERROR: $aTemp is not a valid temp file"
	exit 1
fi

# iterate through all files (arguments)
for f in `ssh ${MASTER_ACCOUNT} find "$*" -maxdepth 1 -type f`; do
	aScpError=`scp -q ${MASTER_ACCOUNT}:$f $aTemp 2>&1`
	if [ "$?" = "0" ]; then
		diff $aOpts $aTemp $f | sed -e "s|$aTemp|master:$f|" -e "s|^Files master:\(.*\) and \(.*\) differ$|\1 differs|"
	else
		echo "$aScpError" | sed "s|scp: |master:|"
	fi
done

# clean up temp file
rm -f $aTemp

