#!/bin/bash
cd "${HOME}/.dotfiles" || (
	echo ":: Error: Can't cd into ${HOME}/.dotfiles"
	exit 1
)

# Colors
COLOR="31"
COLOR_REGULAR="\e[0;${COLOR}m"
COLOR_BOLD="\e[1;${COLOR}m"
COLOR_RESET="\e[0m"

# Latest commit
if curl -qsI https://git.staropensource.de|head -1|grep " 200" &> /dev/null; then
	COMMIT=$(env PAGER= git log -n 1 --pretty=format:\"%H\")
	LATEST_COMMIT=$(curl -sX 'GET' 'https://git.staropensource.de/api/v1/repos/JeremyStarTM/punktdateien/branches/develop' -H 'accept: application/json'|jq --monochrome-output '.commit.id')
	LATEST_COMMIT_MESSAGE=$(curl -sX 'GET' 'https://git.staropensource.de/api/v1/repos/JeremyStarTM/punktdateien/branches/develop' -H 'accept: application/json'|jq --monochrome-output '.commit.message'|sed 's/\\n//g')
else
	[[ -z "${SCRIPTED}" ]] && echo -e "${COLOR_BOLD}https://git.staropensource.de is not reachable"
	exit 1
fi

if [ "${COMMIT}" == "${LATEST_COMMIT}" ] || [ -z "${LATEST_COMMIT}" ]; then
	UPDATE=
else
	UPDATE=true
fi

if [ -z "${SCRIPTED}" ]; then
	if [ -n "${UPDATE}" ]; then
		echo -e  "${COLOR_BOLD}An update for jstm's punktdateien is available."
		echo -e  "${COLOR_REGULAR}Latest commit: ${LATEST_COMMIT}"
		echo     "   -> Message: ${LATEST_COMMIT_MESSAGE}"
		echo     ""
		echo -e  "${COLOR_BOLD}Update by executing \"dotfiles-updater\""
		echo -en "${COLOR_RESET}"
		exit 0
	elif [ -z "${BASHRC}" ]; then
		echo -e "${COLOR_BOLD}No update available"
		exit 1
	fi
else	
	if [ -n "${UPDATE}" ]; then
		echo "${LATEST_COMMIT_MESSAGE}"
	fi
fi