#!/bin/bash

SCOPE_ADDRESS=""
IMAGE_PATH="."
DATA_BUFFER="dataBuffer.png"
DISPLAY_BUFFER="displayBuffer.png"
SLEEP_TIME=2
ARG=""
FUNC="usage"

function usage {
    echo "usage: `basename \"$0\"` [option]"
    echo ""
    echo "Options:"
    echo "    -a <address>  Specify the scope <address>"
    echo "    -h            Show help."
    echo "    -c <command>  Send <command> to scope"
    echo "    -m            Clear menu"
    echo "    -p <path>     Path to store dataBuffer.png and displayBuffer.png"
    echo "    -r            Periodically refresh display buffer every $SLEEP_TIME seconds."
    echo "    -s <setup>    Choose <setup> number (1-4)"
    echo ""

    exit 0
}

function writeScreenshotToDataBuffer {
    curl "http://$SCOPE_ADDRESS/Image.png" -s -o "$IMAGE_PATH/$DATA_BUFFER" 
}


function periodicallyRefreshDisplayBuffer {
while [ true ]
do
    writeScreenshotToDataBuffer
    
    # Does the file exist?
    if [ -f "$IMAGE_PATH/$DATA_BUFFER" ]
    then
        # Test the file size -- only copy if size is greater than 10000 bytes
        IMG_SIZE=`du -b "$IMAGE_PATH/$DATA_BUFFER" | cut -f 1`

        if [ $IMG_SIZE -gt 10000 ]
        then
            # Test the data buffer file contents -- Make sure it's a PNG or EDM will crash
            file default.html | grep -i "PNG image data" >& /dev/null
            IS_PNG=$?

            if [ IS_PNG ]
            then
                # Move the data buffer to the display buffer
                mv "$IMAGE_PATH/$DATA_BUFFER" "$IMAGE_PATH/$DISPLAY_BUFFER"
            fi

        fi

    fi
    sleep "$SLEEP_TIME";
done

exit 1
}

function startDaemon {
    nohup bash "$0" -r -a "$SCOPE_ADDRESS" -p "$IMAGE_PATH" >& /dev/null &
}

function sendCommand {
    COMMAND="$1"

    curl "http://$SCOPE_ADDRESS/Comm.html" -s --data COMMAND="$COMMAND" >& /dev/null
    exit $?;
}

function chooseSetup {
    SETUP="$1"

    sendCommand "RECALL:SETUP+$SETUP"
}

function menuOff {
    sendCommand ":CLEARMENU"
}


while getopts "ha:rdimc:s:p:" optionName; do
case "$optionName" in
      h) FUNC="usage";;
      a) SCOPE_ADDRESS="$OPTARG";;
      d) FUNC="startDaemon";;
      r) FUNC="periodicallyRefreshDisplayBuffer";;
      m) FUNC="menuOff";;
      i) FUNC="writeScreenshotToDataBuffer";;
      c) FUNC="sendCommand"; ARG="$OPTARG";;
      s) FUNC="chooseSetup"; ARG="$OPTARG";;
      p) IMAGE_PATH="$OPTARG";;
    [?]) FUNC="usage";;
esac
done

if [ -z "$SCOPE_ADDRESS" ]
then
    echo "`basename \"$0\"`: No scope address specified."
    usage
fi

"$FUNC" "$ARG"


