#!/bin/sh

set -eu

IS_LOG="${AUTOPKGTEST_ARTIFACTS}/is_savegames.log"

NOSOUND=1
export NOSOUND

# keytyping delay in milliseconds
D=900
# sleep between some slower actions, in seconds
S=5

is > "${IS_LOG}" &
#IS_PID=$!

# click begin new game
xdotool search --sync --all --onlyvisible --name Ironseed \
  windowfocus --sync %1 \
  set_window --name "is_startup" \
  key --clearmodifiers Escape \
  sleep $S mousemove --sync --window %1 200 350 \
  sleep $S click --clearmodifiers 1

# screenshot (main game start menu)
xwd -silent -root -out "${AUTOPKGTEST_ARTIFACTS}/savegames_1.xwd"
  
# complete crewgen and save in slot1
xdotool search --sync --all --onlyvisible --name Ironseed \
  windowfocus --sync %1 \
  set_window --name "is_crewgen" \
  mousemove --sync --window %1 580 350 \
  sleep $S click --clearmodifiers 1 \
  sleep $S \
  key --clearmodifiers --delay $D Return \
  Return Return Return Return Return Return Return Return \
  1 Return T Return \
  sleep $S mousemove --sync --window %1 595 435 \
  sleep $S

# screenshot (first in-game message "Greetings & hallucionations" arrives)
xwd -silent -root -out "${AUTOPKGTEST_ARTIFACTS}/savegames_2.xwd"
xwdtopnm -quiet < "${AUTOPKGTEST_ARTIFACTS}/savegames_2.xwd" > "${AUTOPKGTEST_ARTIFACTS}/savegames_2.pnm"

# start game and save in slot2
xdotool search --sync --all --onlyvisible --name Ironseed \
  windowfocus --sync %1 \
  set_window --name "is_main" \
  key --clearmodifiers --delay $D Escape \
  b e 2 Return X Return \
  sleep $S

# screenshot (normal game view orbiting planet)
xwd -silent -root -out "${AUTOPKGTEST_ARTIFACTS}/savegames_3.xwd"

# exit game
xdotool search --sync --all --onlyvisible --name is_main \
  windowfocus --sync %1 \
  key --clearmodifiers --delay $D alt+x y

# wait for game to finish and cleanup
if grep -vi '^ironseed' "${IS_LOG}"
then
	echo >&2 "Unrecognized game output"
	exit 21
fi

wait
