#!/bin/bash
# (c) 2016 Freifunk Hochstift <kontakt@hochstift.freifunk.net>
#

DEFAULT_DIR="{{salt['pillar.get']('nodes:' ~ grains['id'] ~ ':path:firmware', [])}}"
DEFAULT_BRANCHES="stable testing experimental"

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


function createChangelog {
	VERSION=$1
	VERSION_DIR=${FIRMWARE_DIR}/${VERSION}

	if [ ! -d "${VERSION_DIR}" ]; then
		echo "${VERSION} directory not found (${VERSION_DIR})."
		return 1
	fi

	rm -f ${VERSION_DIR}/Changelog.html
	if [ -r "${VERSION_DIR}/Changelog.md" ]; then
		[ "${VERBOSE}" -eq "1" ] && echo "create ${VERSION}/Changelog.html"
		pandoc -f markdown -t html5 -o ${VERSION_DIR}/Changelog.html -s -V pagetitle="FFHO Changelog (${VERSION})" ${VERSION_DIR}/Changelog.md > /dev/null
		[ "$?" -eq "0" ] || echo "failed to create ${VERSION}/Changelog.html"
	fi

	return 0
}

[ -n "${FIRMWARE_DIR}" ] || FIRMWARE_DIR=${DEFAULT_DIR}
[ -n "${FORCE}" ] || FORCE=0
[ -n "${BRANCHES}" ] || BRANCHES=${DEFAULT_BRANCHES}
[ -n "${VERBOSE}" ] || VERBOSE=0

if [ ! -d "${FIRMWARE_DIR}" ]; then
	echo "Firmware directory not found (${FIRMWARE_DIR}). Cannot update."
	exit 1
fi
if [ ! -d "${FIRMWARE_DIR}/.git" ]; then
	echo "Firmware directory does not seem to be a git repository. Cannot update."
	exit 1
fi

pushd ${FIRMWARE_DIR} > /dev/null

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

if [ "$(git status --porcelain --untracked-files=no)" ]; then
	echo "Local changes to firmware directory. Cowardly refusing to update firmware-website.git!" >&2
	exit 1
fi

[ "${VERBOSE}" -eq "1" ] && echo "pull changes from remote repository"
if ! git pull --quiet --rebase > /dev/null; then
	echo " => Update of firmware-website.git failed... :-(" >&2
	exit 2
fi

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

if [ "${LAST_REVISION}" != "${NEW_REVISION}" ] || [ "${FORCE}" -eq "1" ]; then
	for folder in *; do
		if [ -d "${folder}" -a ! -L "${folder}" ]; then
			createChangelog ${folder}
		fi
	done
	[ "${VERBOSE}" -eq "1" ] && echo ""

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

	# Update models.json
	scripts/buildModels.py stable models.json

	echo "Firmware-Website updated: ${num_commits} commit(s) (last: ${last_msg})"
fi
[ "${VERBOSE}" -eq "1" ] && echo "Finish"
popd > /dev/null #${FIRMWARE_DIR}