#!/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

WORKING_DIRECTORY='../data/'
TEST_LOCK="$WORKING_DIRECTORY/testlock"
TEST_LOG="$WORKING_DIRECTORY/log"
ODDMUSE_TEST_LOCATION="$WORKING_DIRECTORY/oddmuse-for-tests/"
GIT_LOCATION="$WORKING_DIRECTORY/"
LAST_COMMIT_FILE="$WORKING_DIRECTORY/last_commit"
LAST_STATUS_FILE="$WORKING_DIRECTORY/last_status"
FIRST_TESTABLE_COMMIT='1c0801bd6ca23de71c7c360a18a648c2b953f1da'
RESULT_FILE="$WORKING_DIRECTORY/output"
WIKIPUT='../config/oddmuse/scripts/cli/wikiput'
STATUS_PAGE='Test Status'
OUT_PAGE='https://github.com/AlexDaniel/oddmuse-alexine-data/blob/master/output'
WIKI_LOCATION='https://oddmuse.org/wiki/'
USER_NAME='Alexine'

clean() {
  while popd &> /dev/null; do :; done # change directory back
  rmdir -- "$TEST_LOCK"
}

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

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

git=('git' '--git-dir' "$ODDMUSE_TEST_LOCATION/.git" '--work-tree' "$ODDMUSE_TEST_LOCATION")
gitRepo=('git' '--git-dir' "$WORKING_DIRECTORY/.git" '--work-tree' "$WORKING_DIRECTORY") # our repo where we will make commits
while :; do
  "${git[@]}" fetch # get latest changes
  "${git[@]}" reset --hard origin/master # starting our search from the last commit

  [[ -f $LAST_COMMIT_FILE ]] || echo "$FIRST_TESTABLE_COMMIT" > "$LAST_COMMIT_FILE"
  [[ -f $LAST_STATUS_FILE ]] || echo 0 > "$LAST_STATUS_FILE"
  lastCommit=$(< "$LAST_COMMIT_FILE")
  lastStatus=$(< "$LAST_STATUS_FILE")

  logOutput=$("${git[@]}" log --topo-order --pretty=oneline | grep --before 1 -m 1 "^$lastCommit")
  (($(wc -l <<< "$logOutput") < 2)) && exit 0 # No more commits to process, good!
  read -r currentCommit _ <<< "$logOutput"

  "${git[@]}" checkout "$currentCommit"
  # ((startTime = SECONDS)) ||:
  pushd -- "$ODDMUSE_TEST_LOCATION" || exit 1
  output=$(make test jobs=8 2>&1) &&:
  status=$?
  popd
  # ((duration = SECONDS - startTime)) ||:
  printf "%s\n" "$output" > "$RESULT_FILE"
  # echo "Duration: $((duration/60))m$((duration%60))s Status: $status" >> "$RESULT_FILE"
  printf "%s\n" "$currentCommit" > "$LAST_COMMIT_FILE"
  printf "%s\n" "$status"        > "$LAST_STATUS_FILE"

  "${gitRepo[@]}" add -- "$(readlink -m -- "$RESULT_FILE")" "$(readlink -m -- "$LAST_COMMIT_FILE")" "$(readlink -m -- "$LAST_STATUS_FILE")"
  "${gitRepo[@]}" commit -m "Test status at $currentCommit (automated commit)"

  "${gitRepo[@]}" push

  if (( status == 0 )); then
    (( lastStatus == 0 )) && minor='-m' || minor='' # we will use unquoted variable on purpose
    "$WIKIPUT" $minor -u "$USER_NAME" -s 'Tests PASSED' -z 'ham' "$WIKI_LOCATION/$STATUS_PAGE" <<< $'TEST STATUS – **OK**\n\n'"Commit:${currentCommit:0:7} – see [[$OUT_PAGE|test log]]"
  else
    "$WIKIPUT" -u "$USER_NAME" -s 'Tests FAILED' -z 'ham' "$WIKI_LOCATION/$STATUS_PAGE" <<< $'TEST STATUS – **FAIL**\n\n'"Commit:${currentCommit:0:7} – see [[$OUT_PAGE|test log]]"
  fi
done
