#!/bin/bash

HELPTEXT="
Script that runs the rrule_manager unit tests on different dates.

Prerequisites: 
* PHPUnit must be set up. (php admin/tool/phpunit/cli/init.php)

Usage:
1. Go to the moodle instance root where this script is installed. 
2. Run script: e.g.
   sudo bash ./rruletest.sh -p [PATH TO OUTPUT FILE] -y [YEAR LIMIT]

Options:
  -p Optional. The path to the output file. 
     Defaults to ./rruletestoutput.txt
  -y Optional. The maximum year the tests will be run against with. 
     Defaults to the current year.
"
usage() { echo "$HELPTEXT" 1>&2; exit 1; }

if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root"
   exit 1
fi

while getopts ":p:y:" o; do
    case "${o}" in
        p)
            OUTPUTFILE=${OPTARG}
            ;;
        y)
            YEARLIMIT=${OPTARG}
            ;;
        \?)
            usage
            ;;
    esac
done

# Get current year
CURRENTYEAR=`date +%Y`

# Set default value for the year until the tests will be run. 
if [ -z "$YEARLIMIT" ]; then
    YEARLIMIT=$CURRENTYEAR
fi

# Set output file default.
if [ -z "$OUTPUTFILE" ]; then
    OUTPUTFILE="./rruletestoutput.txt"
fi

# Disable NTP.
timedatectl set-ntp false

echo "Running tests. Detailed results can be found in $OUTPUTFILE"

# Run the tests!
while [ $CURRENTYEAR -le $YEARLIMIT ]
do
    date
    echo "Running tests for `date`:" >> $OUTPUTFILE
    echo "" >> $OUTPUTFILE
    # Run the tests for the current day.
    vendor/bin/phpunit calendar/tests/rrule_manager_test.php >> $OUTPUTFILE
    STATUS=$?
    echo "" >> $OUTPUTFILE

    if [[ $STATUS -eq 0 ]]; then
        echo "Passed!"
    else
        echo "Failed!"
    fi
    echo

    # Increment the date to tomorrow.
    TOMORROW=`date --set=tomorrow`

    # Keep tab of the current year.
    CURRENTYEAR=`date +%Y`
done

# Reenable NTP.
timedatectl set-ntp true
