#!/bin/bash
#
# __copy1__
# __copy2__
#
# search Documents directory and try to auto-update all
# bazaar instances (update or commit)
#
CMD=`basename $0`
LOGFILE="$HOME/.$CMD.log"
LOGSYSLOG="false"
KU_LOCKFILE="$HOME/$CMD.lock"

# get functions
. /lib/ku-base/log.sh
. /lib/ku-base/lock.sh

usage()
{
	echo "
usage: $CMD [options] [dir(s) ...]

options:
  -q|--quiet	do not display progress messages (but warning still do)
  --autocommit	do 'bzr commit' instead of 'bzr update'
  -l|--list	only list directories

if not given, the dir list is taken from \$HOME/.oz-bzr-autoupdate file
if present, or from all the Documents/* bazaar directories; use --list
option to show actual dir list

" >&2
	exit 1
}


do_autoupdate()
{
	ku_log "updating $repo ..."
	bzr update || {
		oz-message "ERROR during update of $repo"
		# FIXME inserire qui la gestione del logfile
		#	e dell'errore
	}

	# clean up conflicts mess (extensions mess)
	#
	local ext=
	local file=
	local msg=
	local fname=
	local fext=

	for ext in BASE OTHER THIS
	do
		find * -name "*.$ext" | while read file
		do
			fname=`echo "$file" | sed -e "s/\.${ext}$//"`
			fext=`echo "$fname" | sed -e "s/.*\.\([^.]*\)$/\1/"`
			fname=`echo "$fname" | sed -e "s/\.${fext}$//"`
			case $ext in
				BASE)	fname="$fname.MERGED.$fext" ;;	# merged?
				OTHER)	fname="$fname.UPDATED.$fext" ;;	# the updated one
				THIS)	fname="$fname.$fext" ;;		# restore local one
			esac
			mv "$file" "$fname"
		done
	done

	msg=`
		bzr status | grep "Contents conflict in" | \
			sed -e 's/.*Contents conflict in //'
		for ext in MERGED UPDATED
		do
			find * -name "*.$ext.*"
		done | sort`

	[ "$msg" != "" ] && {
		fname=`pwd` ; fname=`basename $fname`
		msg="ATTENZIONE! Rilevati conflitti in $fname.\nControllare questi files:\n\n$msg"
		msg="$msg\n\nNota: i conflitti sono stati risolti automaticamente"
		msg="$msg\nper poter eseguire il prossimo commit, quindi i files"
		msg="$msg\ndovranno essere controllati e cancellati manualmente."
		oz-message "$msg"
	}

	bzr status | grep "Contents conflict in" | \
		sed -e 's/.*Contents conflict in //' | while read file
	do
		bzr resolve "$file"
	done
}


do_autocommit()
{
	ku_log "auto-committing $repo ..."
	[ X"`bzr status`" != "X" ] && {
		bzr add || return $?
		bzr commit -m "(autocommit)" || {
			ku_log "ERROR during commit on $repo"
			oz-message "ERROR during commit on $repo"
			# FIXME inserire qui la gestione del logfile
			#	e dell'errore
		}
	}
}

cd_repo_home()
{
	while :
	do
		[ "`pwd`" = "/" ] && {
			oz-message "directory '$repo' is not a bazaar repo"
			return 1 # not found
		}
		[ -d .bzr ] && break
		cd ..
	done
	return 0 # OK, found
}

# (MAIN)

VERBOSE=true
f_autocommit=false
f_list=false
dirlist=

while [ $# != 0 ]
do
    case $1 in
	-v|--verbose)		VERBOSE=true ;;
    	-q|--quiet)		VERBOSE=false ;;
  	--autocommit)		f_autocommit=true ;;
	-l|--list)		f_list=true ;;
	--)			break ;;
	-*)			usage ;;
	*)			dirlist="$dirlist $1" ;;
    esac
    shift
done
[ $# != 0 ] && dirlist="$dirlist $*"

# se elenco repo bazaar non passati da riga comando, guarda prima
# contenuto del file $HOME/.oz-bzr-autoupdate, e se non esiste
# cerca tutte le directories di primo livello sotto Documenti o
# Documents
#
[ "$dirlist" == "" ] && {
	[ -f $HOME/.oz-bzr-autoupdate ] && dirlist=`cat $HOME/.oz-bzr-autoupdate`
}
[ "$dirlist" == "" ] && {
	cd $HOME
	dirlist=`ls -d Document*/*/.bzr 2>/dev/null | sed -e 's/\/\.bzr//'`
}
[ "$dirlist" == "" ] && exit 0

here=`pwd`
dirlist=`echo "$dirlist" | sed -e 's/\/\.bzr//g'`

# purge dirlist
#
newdirlist=
for dir in $dirlist
do
	if [ -d $dir/.bzr ]
	then
		newdirlist="$newdirlist $dir"
	else
		ku_log " not a bazar dir, skipped $dir" >&2
	fi
done
dirlist=`echo $newdirlist`

# only listing?
#
$f_list && {
	echo $dirlist
	exit 0
}


ku_cap_logfile
if $f_autocommin
then
	ku_log "started autocommit"
else
	ku_log "started autoupdate"
fi

ku_lock || {
	ku_log "already running"
	exit 0
}
trap "ku_log '*INTR*'; ku_lock_remove; exit 255" 1 2 3


if $VERBOSE
then
	exec 2>&1 | tee -a $LOGFILE
else
	exec >>$LOGFILE 2>&1
fi

for repo in $dirlist
do
	if echo "$repo" | grep -q "^/"
	then
		cd $repo		# absolute path
	else
		cd $here/$repo		# relative path
	fi
	cd_repo_home || continue

	if $f_autocommit
	then
		do_autocommit
	else
		do_autoupdate
	fi
done

ku_lock_remove
sleep 2

ku_log "ended"
exit 0
