#!/bin/bash

# Configuration:
	# Where the marker file is kept. This should be
	# accessible to all machines that share the
	# portage tree, but should obviously NOT be
	# inside the portage tree itself.
GODIR="/keeps/gentoo"

	# Which sync command would you like to use?
	# Simplest would be 'emerge --sync', but do
	# take care to find a good outlet for output,
	# like a log file. Other examples are
	# `eix-sync' (app-portage/eix) and
	# `eupdatedb' (app-portage/esearch [DEPRECATED]).
SYNCCMD="/usr/bin/eix-sync"
	# Don't forget to set the proper --metadata
	# option for SYNCCMD running on P-Tree clients:
SYNCOPTS="-m"
	# Which host does the actual syncing? - Note that
	# only one host syncs, the others just cache
	# metadata.
SYNCHOST="misha"
	# Wait this many seconds before re-attempting SYNCCMD:
SYNCWAIT="10"
	# TODO: Put the pid file to better use.
	# Where to put the pid file:
PIDFILE="/var/run/syncportage.pid"

#export PORTDIR_OVERLAY="/keeps/gentoo/local /keeps/gentoo/cvs/gentoo-x86"

# Auto-Setup:
thisdomain="$( which dnsdomainname &>/dev/null && dnsdomainname || domainname )"
SYNCLIST="${GODIR}/.syncing"
mynow="$(date)"
synccmd="${SYNCCMD}"

# Append hostname to SYNCLIST
echo "${HOSTNAME}" >> ${SYNCLIST}

# Check whether to run --sync or --metadata:
if test "${HOSTNAME}" != "${SYNCHOST}"; then
	# Does SYNCCMD exist? If not, default to emerge --metadata.
	if ! test -x "$(type -P ${SYNCCMD})"; then
		synccmd="emerge"
		syncopts="--metadata --nospinner"
		echo " * ${SYNCCMD} does not exist; defaulting to ${synccmd} ${syncopts}"
	else
		syncopts="${SYNCOPTS}"
	fi
fi

if test "${HOSTNAME}" = "${SYNCHOST}"; then
	# Help the sync host shorten the rsync session:
	export PORTAGE_NICENESS="0"
fi

# Check if synccmd happens to be running:
if grep -qa "$(type -P ${synccmd}) ${syncopts}" /proc/[0-9]*/cmdline 2>&1 >/dev/null; then
	echo "${synccmd} is already running. Exiting immediately..."
	exit
fi

# With -f, remove PIDFILE, check that we are the host that --sync's and continue:
if test "${1}x" = "-fx"; then
	echo " * Forcing this host to sync now..."
	test "${HOSTNAME}x" = "${SYNCHOST}x" && \
		rm -f ${PIDFILE}
fi

# TODO: Why should PIDFILE exist, unless this script is buggy?
if test -f "${PIDFILE}"; then
	echo " * PID file exists. Exiting now."
	exit
else
	echo ${$} > "${PIDFILE}"
fi

# Just do it:
echo "${HOSTNAME}.${thisdomain} ${mynow}"

# Check if this host is top of the list, else wait:
while test "$( head -n 1 ${SYNCLIST} )x" != "${HOSTNAME}x"; do
	# Someone else is syncing/caching: Wait a while and repeat:
	sleep ${SYNCWAIT}
done

# Finally run synccmd:
echo " * Attempting to run ${synccmd} ${syncopts} ..."
echo

# Run sync command
time ${synccmd} ${syncopts}

# Remove hostname from SYNCLIST when done
sed -e "/${HOSTNAME}/d" -i ${SYNCLIST}

rm -f ${PIDFILE}

# Clean up:
unset thisdomain 
unset GODIR 
unset SYNCLIST 
unset mynow 
unset SYNCCMD
unset SYNCOPTS
unset synccmd
unset syncopts
unset SYNCWAIT

