#!/bin/bash
# Copyright (C) 2015  Alex-Daniel Jakimenko <alex.jakimenko@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
set -e

RELEASE_LOCK='../data/releaselock'
ODDMUSE_LOCATION='../data/oddmuse-for-releases/'
WIKIPUT='../config/oddmuse/scripts/cli/wikiput'
WIKI_LOCATION='https://oddmuse.org/wiki/'
USER_NAME='Alexine'

clean() {
  rmdir -- "$RELEASE_LOCK"
}

[[ -d $ODDMUSE_LOCATION ]] || git clone -- 'https://github.com/kensanata/oddmuse.git' "$ODDMUSE_LOCATION"

if mkdir -- "$RELEASE_LOCK"; then # only one instance running
  trap clean EXIT
else
  exit 0
fi

git=('git' '--git-dir' "$ODDMUSE_LOCATION/.git" '--work-tree' "$ODDMUSE_LOCATION")
"${git[@]}" fetch # get latest changes
"${git[@]}" reset --hard origin/master # move to the last commit

# lastRelease=$("${git[@]}" tag -l --sort='-version:refname' | head -n 1) # old git versions can't do that
lastRelease=$("${git[@]}" tag -l | sort -rV | head -n 1)

pageText=$(curl -- "$WIKI_LOCATION/Local_Intermap?raw=1")

"$WIKIPUT" -u "$USER_NAME" -s 'New release' -z 'ham' "$WIKI_LOCATION/Local_Intermap" < <(sed 's/[0-9]\+\.[0-9]\+\.[0-9]\+'"/$lastRelease/g" <<< "$pageText")
