#!/bin/bash -e
#
# Attempt to bump the appc/spec version to the version specified in
# glide.yaml by replacing all occurrences of the current/previous
# version. The old version is taken from stage1/aci/aci-manifest.in.
#
# YMMV, no disclaimer or warranty, etc.

# make sure we are running in a toplevel directory
if ! [[ "$0" =~ "scripts/bump-appc-spec-version" ]]; then
	echo "This script must be run in a toplevel rkt directory"
	exit 255
fi

function replace_stuff() {
	local FROM
	local TO
	local REPLACE

	FROM=$1
	TO=$2
	# escape special characters
	REPLACE=$(sed -e 's/[]\/$*.^|[]/\\&/g'<<< $FROM)
	shift 2
	echo $* | xargs sed -i --follow-symlinks -e "s/$REPLACE/$TO/g"
}

function replace_all() {
	replace_stuff $1 $2 $(git ls-files | grep -Ev "(CHANGELOG.md|vendor|manifest\.d|glide.lock|glide.yaml)")
}

PREV=$(grep -Pe 'acVersion' stage1/aci/aci-manifest.in | grep -Po '\d+\.\d+\.\d+')
NEXT=$(grep -A 1 -e '^- package: github.com/appc/spec$' glide.yaml | grep -Po '\d+\.\d+\.\d+')

if [[ ${PREV} = ${NEXT} ]]; then
	exit 0
fi

replace_all $PREV $NEXT
