#!/bin/bash

usage() {
    printf "Usage: %s scriptfile.xte outputdir\n\n" `basename "$0"`
}

xteevent() {
    echo "$1"
    if echo "$1" |grep -q "^key"; then
        echo "usleep 250000"
    fi
}

if [ ! -e "$(which xte)" ]; then
    echo "You need the xte utility. On Debian/Ubuntu, apt-get install xautomation"
    exit 1
fi

if [ ! -e "./rockboxui" ]; then
    echo "You need to run this script while inside a simulator builddir"
    exit 2
fi

if [ ! -f "$1" ]; then
    usage
    printf "File not readable: %s\n" "$1"
    exit 3
fi

if [ ! -d "$2" ]; then
    usage
    printf "Not a directory: %s\n" "$2"
    exit 4
fi

# Make sure we have a clean slate
killall rockboxui
rm -f simdisk/*.bmp

# Launch the sim
./rockboxui &

# Loop through lines of the input file and pass them to xte
grep -v "^#" "$1" \
    |sed 's/Screenshot/key F5/' \
    |sed 's/#.*//' \
    |(
        echo "sleep 5" # Sleep for 5 seconds before doing anything
        while read line; do
            # If a line starts with a number, repeat the event that follows
            # that many times
            if echo "$line" |grep -q "^[0-9]\+ "; then
                repeat=$(echo "$line"|sed 's/ .*//')
                line=$(echo "$line"|sed 's/[0-9]\+ //')
                while [ $repeat -gt 0 ]; do
                    repeat=$(expr $repeat - 1)
                    xteevent "$line"
                done
            else
                xteevent "$line"
            fi
        done) \
    |tee xte.log \
    |xte

# Wait until the amount of screenshots in the simdisk dir matches the amount
# listed in the script. Let's pray nothing went wrong!
while [ $(ls simdisk/dump*.bmp |wc -l) -lt $(grep -c "^# Screenshot" "$1") ]; do
    sleep 1
done

file=1
grep "^# Screenshot " "$1"|(
display=$(grep "^# Display " "$1" |sed 's/^# Display //')
outdir=$2
while read line; do
    # This looks nasty, but it basically does the following:
    # Prepend a slash
    # Add ss- after the last slash (possibly the one we just added)
    # Prepend the outputdir
    # Append -$display.png
    to=$(echo "$line"|sed -e "s@\(.* \)@\\1/@" -e "s@\(.*/\)@\\1ss-@" -e "s@^# Screenshot @${outdir}/@" -e "s@\$@-${display}.png@")

    from=$(ls simdisk/dump*.bmp|head -n $file|tail -n 1)
    # Create the output dir if it doesn't exist already
    mkdir -p "$(dirname "$to")"
    convert "$from" "$to"
    echo $to
    file=$(expr $file + 1)
done
)

# Kill all huma^H^H^H^Hsimulators
killall rockboxui
# Clean up
rm -f simdisk/*.bmp
