#!/bin/bash

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

event() {
    if echo "$1" |grep -q "^SCREENSHOT"; then
        echo $1 >&2
        echo "SCREENSHOT"
        sleep 1
    elif echo "$1" |grep -q "^SYS_USB_"; then
        echo "$1"
        sleep 0.2
    elif echo "$1" |grep -q "^SLEEP "; then
        sleep $(echo "$1" |sed 's/^SLEEP //')
    elif echo "$1" |grep -q " REL$"; then
        printf "BUTTON_%s\n" "$1"
    elif echo "$1" |grep -q " REPEAT$"; then
        printf "BUTTON_%s\n" "$1"
    elif echo "$1" |grep -q "^SCROLL"; then
        printf "BUTTON_%s\n" "$1"
#        sleep 0.5
    else
        printf "BUTTON_%s\n" "$1"
        sleep 0.1
        printf "BUTTON_%s REL\n" "$1"
        sleep 0.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 > /dev/null 2>&1
rm -f simdisk/*.bmp

# Set up our pipe
rm -f fifo
mkfifo fifo

sleep 1
# Launch the sim
./rockboxui --cmdpipe fifo --nobackground & # > /dev/null 2>&1 &
sleep 1

# Loop through lines of the input file and pass them to the fifo 
grep -E -v "(^#|^$)" "$1" \
    |tr [a-z] [A-Z] \
    |sed 's/#.*//' \
    |sed 's/ *$//' \
    |(
    sleep 5
    while read line; do
        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)
                event "$line"
            done
        else
            event "$line"
        fi
    done
    ) > fifo

file=1
grep -i "^SCREENSHOT " "$1"|(
display=$(grep -i "^# DISPLAY " "$1" |sed 's/^# DISPLAY //i')
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}/@i" -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
)

# Clean up
#rm -f simdisk/*.bmp
