#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"


if [ ! -f "$DIR/.testConfig" ]; then
	        echo "Missing configuration"
		        exit 1
fi
source $DIR/.testConfig

scriptDir="$gitDir"/oxguard-ui/testScripts

cd "$gitDir"
git pull

if [ -e "$tmpFile" ]; then
	oldHash=$(<"$tmpFile")
	echo "Old Hash: " $oldHash
else
	oldHash=""
	echo "No history file found"
fi

newHash=$(git log -1 --format=%H)
echo "New Hash: " $newHash
if [ "$newHash" == "$oldHash" ]; then 
  echo "Same, exiting"
  exit 0
fi

echo "Different, running tests"
git log -1 --format=%H > "$tmpFile" 

"$scriptDir"/fastUpdate all

echo "Restarting OX...."
systemctl restart open-xchange
echo "Wating for restart of open-xchange
"
sleep 10
# Wait for port avail
while ! nc -z localhost 8009 </dev/null; do sleep 10; done
echo "Port open.  Waiting for stabilization...
"
sleep 10
/opt/open-xchange/sbin/runallupdate -A oxadminmaster -P secret
sleep 5

cd "$gitDir"/oxguard-ui
rm -r build/e2e
yarn && yarn e2e --grep "$GrepTests" 
rm -r "$gitDir"/oxguard-ui/allure-report
"$gitDir"/oxguard-ui/node_modules/allure-commandline/bin/allure generate build/e2e

# Get total results from history json
totalCount=0;
for row in $(jq '.[].statistic.total' "$gitDir"/oxguard-ui/allure-report/history/history.json)
  	do
    	totalCount=$(($totalCount+$row))
	done
totalPassed=0;
for row in $(jq '.[].statistic.passed' "$gitDir"/oxguard-ui/allure-report/history/history.json)
  	do
    	totalPassed=$(($totalPassed+$row))
	done
totalFailed=0;
for row in $(jq '.[].statistic.failed' "$gitDir"/oxguard-ui/allure-report/history/history.json)
  	do
    	totalFailed=$(($totalFailed+$row))
	done


echo Total tests: $totalCount
echo Tests passed: $totalPassed

urlLink="http://$EXTIP/report"
if [ "$totalCount" != "$totalPassed" ]; then 
	echo "Not all passed"
	cd  "$gitDir"/oxguard-ui/allure-report
	zip -r report.zip *
	packageList=$(cat $aptFile)

	message="Guard UI tests results:
	Total:"$totalCount"
	Passed:"$totalPassed"
	Failed:"$totalFailed"
	
	Latest report: $urlLink
	----------------
	
Packages:
"$packageList""
	printf '%s' "$message" | mutt -s "UI Test result" -a report.zip -e "set envelope_from=yes" -e "set from=$FROM" -- "$TO"
else
	printf "All Guard UI tests Green" | mutt -s "UI Test result" -e "set envelope_from=yes" -e "set from=$FROM" -- "$TO"
fi


