#!/bin/sh

set -eu

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

uqm --sound=none --logfile="${UQM_LOG}" >&2 &

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

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

sleep 2

# 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 2 \
  key --clearmodifiers --delay 1500 Return Escape \
  sleep 1

# 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 500 Escape \
  Down Down Return Return \
  sleep 1 \
  key Return \
  sleep 1 \
  type 'testsave'

sleep 1

# 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 500 Return \
  sleep 1 \
  key --clearmodifiers --delay 500 Return Down Down Return Left Return \
  sleep 1 \
  key --clearmodifiers --delay 500 Up Return

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

wait
