#!/bin/sh

set -eu

DELAY1=750
DELAY3=2200
SLEEP1=2
SLEEP2=4

UQM_LOG="${AUTOPKGTEST_ARTIFACTS}/uqm_savegames.log"

uqm --sound=none 2>&1 | ts -s > ${UQM_LOG} &

# screenshot before xdotool, in case it hangs
sleep ${SLEEP2}
xwd -silent -root -out "${AUTOPKGTEST_ARTIFACTS}/savegames_0.xwd"

# skip intro
xdotool search --sync --all --onlyvisible --name "The Ur-Quan Masters" \
  windowfocus --sync %1 \
  sleep ${SLEEP1} \
  key --clearmodifiers Escape

# screenshot Intro
xwd -silent -root -out "${AUTOPKGTEST_ARTIFACTS}/savegames_1.xwd"

sleep ${SLEEP2}

# screenshot Mainmenu
xwd -silent -root -out "${AUTOPKGTEST_ARTIFACTS}/savegames_2.xwd"

# start new game
xdotool search --sync --all --onlyvisible --name "The Ur-Quan Masters" \
  windowfocus --sync %1 \
  sleep ${SLEEP2} \
  key --clearmodifiers --delay ${DELAY3} Return Escape \
  sleep ${SLEEP1}

# screenshot Sol map
xwd -silent -root -out "${AUTOPKGTEST_ARTIFACTS}/savegames_3.xwd"

# save game in slot1
xdotool search --sync --all --onlyvisible --name "The Ur-Quan Masters" \
  windowfocus --sync %1 \
  key --clearmodifiers --delay ${DELAY1} Escape \
  Down Down Return Return \
  sleep ${SLEEP1} \
  key Return \
  sleep ${SLEEP1} \
  type --delay ${DELAY1} 'testsave'

sleep ${SLEEP1}

# screenshot SaveGame
xwd -silent -root -out "${AUTOPKGTEST_ARTIFACTS}/savegames_4.xwd"

# exit the game
xdotool search --sync --all --onlyvisible --name "The Ur-Quan Masters" \
  windowfocus --sync %1 \
  key --clearmodifiers --delay ${DELAY1} Return \
  sleep ${SLEEP1} \
  key --clearmodifiers --delay ${DELAY1} Return Down Down Return Left Return \
  sleep ${SLEEP1} \
  key --clearmodifiers --delay ${DELAY1} Up Return

# wait for game to finish and cleanup
if ! grep -q 'The Ur-Quan Masters v' "${UQM_LOG}"
then
	echo >&2 "Unrecognized game output"
	exit 21
fi

wait
