#!/bin/sh

set -e

git pull --no-edit

VER=$(grep '^pkgver=' APKBUILD | cut -d '=' -f 2)
CURR_VERSION=$(echo $VER | cut -d '.' -f 1)
CURR_PATCHLEVEL=$(echo $VER | cut -d '.' -f 2)
CURR_SUBLEVEL=$(echo $VER.0 | cut -d '.' -f 3)
CURR_BRANCH=$CURR_VERSION.$CURR_PATCHLEVEL

VERSION=$(curl https://www.kernel.org/releases.json | jq -r '.releases[].version' | grep "^$CURR_VERSION\.$CURR_PATCHLEVEL\.")

if [ ! -n "$VERSION" ];then
	echo "Error: $CURR_BRANCH may be EOLed"
	exit 1
fi

NEW_SUBLEVEL=$(echo "$VERSION" | cut -d '.' -f 3)

if [ ! -n "$NEW_SUBLEVEL" ];then
	exit 0
fi

(if [ "$NEW_SUBLEVEL" -gt "$CURR_SUBLEVEL" ];then
	echo "Update: $CURR_BRANCH.$CURR_SUBLEVEL -> $CURR_BRANCH.$NEW_SUBLEVEL"
	sed "s/pkgver=$VER/pkgver=$CURR_BRANCH.$NEW_SUBLEVEL/" -i APKBUILD
	SED_ERRNO=$?
	abuild checksum
	apkgrel -z APKBUILD
	git add APKBUILD
	if [ "$SED_ERRNO" -eq 0 ];then
		git commit -m "Auto Update: $CURR_BRANCH.$CURR_SUBLEVEL -> $CURR_BRANCH.$NEW_SUBLEVEL"
	else
		git commit -m "[FAILED] Auto Update: $CURR_BRANCH.$CURR_SUBLEVEL -> $CURR_BRANCH.$NEW_SUBLEVEL"
	fi
	git push
fi) || git reset --hard