#!/bin/sh
#
# Simple script to update fastd peers from git upstream
# and only send HUP to fastd when changes happend.
#
# (C) 2014 Helge Jung <hej@c3pb.de>
# (C) 2014 Maximilian Wilhelm <max@rfc2324.org>
#


# CONFIGURE THIS TO YOUR PEER DIRECTORY
DEFAULT_PEERS_DIRECTORY="/etc/freifunk/peers"
SSH_IDENTITY="/root/.ssh/ffho_peers_git.id_rsa"

getCurrentVersion() {
	# Get hash from latest revision
	git log --format=format:%H -1 | tr -d '\n'
}

[ -z "$RELOAD_FASTD" ] && RELOAD_FASTD="yes"

[ -z "$PEERS_DIRECTORY" ] && PEERS_DIRECTORY=$DEFAULT_PEERS_DIRECTORY
if [ ! -d "$PEERS_DIRECTORY" ]; then
	echo "Peers directory not found ($PEERS_DIRECTORY). Cannot update."
	exit 1
fi
if [ ! -d "${PEERS_DIRECTORY}/.git" ]; then
	echo "Peers directory does not seem to be a git repository. Cannot update."
	exit 1
fi
cd "${PEERS_DIRECTORY}"

ssh-add -l > /dev/null 2>&1
if [ "$?" -ne 0 ]; then
	eval $(ssh-agent) > /dev/null
	ssh-add "${SSH_IDENTITY}" 2> /dev/null
	SSH_AGENT_STARTED=yes
else
	SSH_AGENT_STARTED=no
fi

# Get current version hash
LAST_REVISION="$(getCurrentVersion)"

if [ "$(git status --porcelain)" ]; then
	echo "Local changes to peers directory. Cowardly refusing to update this repository!" >&2
	exit 1
fi


if ! git pull --quiet --rebase >/dev/null; then
	echo "Update of peers repository failed... :-(" >&2
	exit 2
fi

# Get new version hash
GIT_NEW_REVISION="$(getCurrentVersion)"

if [ "${LAST_REVISION}" != "${GIT_NEW_REVISION}" ]; then
	if [ "$RELOAD_FASTD" != "no" ]; then
		fastd_pids=$(pidof fastd)
		if [ ! "${fastd_pids}" ]; then
			echo "Oh noes, there is no fastd running here.. Thou shalt fix this now, br0!" >&2
			exit 3
		fi

		kill -HUP ${fastd_pids}
	fi

	# Get list of commits since last local version
	num_commits="$(git log --abbrev-commit --pretty=oneline ${LAST_REVISION}..${GIT_NEW_REVISION} | wc -l)"
	last_msg="$(git log --abbrev-commit --pretty=oneline ${LAST_REVISION}..${GIT_NEW_REVISION} | head -n1)"

	if [ ! -z "$GENALIASES_FILE" ]; then
		./gen_aliases.sh . > "$GENALIASES_FILE"
		ALIASES_UPDATED=1
	else
		ALIASES_UPDATED=0
	fi

	echo -n "Peers"
	if [ $ALIASES_UPDATED -eq 1 ]; then echo -n " and aliases"; fi
	echo " updated: ${num_commits} commits (last: ${last_msg})"
fi

if [ "$SSH_AGENT_STARTED" = "yes" ]; then
	ssh-agent -k > /dev/null
	unset SSH_AGENT_PID
fi