#!/bin/sh
echo "Content-type: text/html; charset=utf-8"
echo
echo "<title>LedTicker</title>"
echo `cat /www/menu.html`

if [ -f /tmp/install.sh ]; then
echo "<pre>`sh /tmp/install.sh`</pre>"
rm -f /tmp/install.sh
fi

LED_PORT=/dev/ttyUSB0

TMP_FILE=/tmp/test.bin
TAIL_FILE=/www/modules/ledticker/tail.bin
CONTENT_FILE=/tmp/ledboard.txt
URL_FILE=/www/modules/ledticker/ledboard_url.txt
LED_PORT_SPEED=38400

SPEED="4"  #1, 2, 3, 4, 5
EFFECT="B" #hold: A,  scroll: B,  snow: C,  flash: D

function update_from_url() {
 URL=""
 if [ -f $URL_FILE ]; then
  URL=`cat $URL_FILE`
 fi
 #echo -n "URL: "
 #echo $URL
 REGEX='^http'
 if [[ $URL =~ $REGEX ]]; then
  if [ -f $CONTENT_FILE ]; then
   OLD_CONTENT=`cat $CONTENT_FILE`
  else
   OLD_CONTENT=""
  fi
  #echo -n "OLD_CONTENT: "
  #echo $OLD_CONTENT
  NEW_CONTENT="`wget -qO- $URL`"
  #echo -n "NEW_CONTENT: "
  #echo $NEW_CONTENT
  if [ "$NEW_CONTENT" ] && [ "$NEW_CONTENT" != "$OLD_CONTENT" ]; then
   echo "UPDATING!";
   MESSAGE=$NEW_CONTENT
   echo -n "$NEW_CONTENT">$CONTENT_FILE
  fi
 else
  echo "URL not set for auto update"
 fi
}

if [ "$REQUEST_METHOD" == "GET" ]; then

function cgi_decodevar() {
    [ $# -ne 1 ] && return
    local v t h
    # replace all + with whitespace and append %%
    t="${1//+/ }%%"
    while [ ${#t} -gt 0 -a "${t}" != "%" ]; do
        v="${v}${t%%\%*}" # digest up to the first %
        t="${t#*%}"       # remove digested part
        # decode if there is anything to decode and if not at end of string
        if [ ${#t} -gt 0 -a "${t}" != "%" ]; then
            h=${t:0:2} # save first two chars
            t="${t:2}" # remove these
            v="${v}"`echo -e \\\\x${h}` # convert hex to special char
        fi
    done
    # return decoded string
    echo "${v}"
    return
}

if [ "$QUERY_STRING" ]; then

  OIFS="$IFS"
  IFS="${IFS}&"
  set $QUERY_STRING
  Args="$*"
  IFS="$OIFS"

  for i in $Args ;do

        OIFS="$IFS"
        IFS="${OIFS}="
        set $i
        IFS="${OIFS}"

        case $1 in
                message) MESSAGE="$(cgi_decodevar $2)"
                       ;;
                url) URL="$(cgi_decodevar $2)"
                       ;;
                speed) SPEED=$2
                       ;;
                effect) EFFECT=$2
                       ;;
                *)     echo "<hr>Warning:"\
                            "<br>Unrecognized variable \'$1\' passed.<hr>"
                       ;;

        esac
  done

  if [ "$URL" != "" ]; then
   echo -n "$URL">$URL_FILE
   update_from_url
  fi

else

  echo "<html><form method='get'>"
  echo "Message: <input type='text' name='message' value=''><br/>"
  echo "Effect: <select name='effect'><option value='A'>A - Hold<option value='B'>B - Scroll<option value='C'>C - Snow<option value='D'>D - flash</select><br/>"
  echo "Speed: <select name='speed'><option>1<option>2<option>3<option>4<option>5</select><br/>"
  echo "URL for auto-update (optional): <input type='text' name='url' value=''><br/>"
  echo "<input type='submit' value='Set'>"
  echo "</form></html>"
  exit;

fi

else
 update_from_url
fi


if [[ "$MESSAGE" != "" ]]
then

echo -n "$MESSAGE">$CONTENT_FILE
#MESSAGE="555"

chr() {
  printf \\$(printf '%03o' $1)
}
ord() {
  printf '%d' "'$1"
}

let sum=0
printf '\x00\x02' > $TMP_FILE

printf '\x31\x06\x00' >> $TMP_FILE
let sum=sum+0x31+0x06+0x00

#speed
echo -n $SPEED >> $TMP_FILE
let sum=sum+$(ord $SPEED)

#???
printf '\x31' >> $TMP_FILE
let sum=sum+0x31

#effect
echo -n $EFFECT >> $TMP_FILE
let sum=sum+$(ord $EFFECT)

#message length
MESSAGE_LENGHT=${#MESSAGE}
chr "${MESSAGE_LENGHT}" >> $TMP_FILE

#message
echo -n "$MESSAGE" >> $TMP_FILE

for ((i=0; i<MESSAGE_LENGHT; i++)); do
   let sum=sum+$(ord ${MESSAGE:$i:1})
   if [[ "${MESSAGE:$i:1}" == " " ]]
   then
    let sum=sum+32
   fi
done

let sum=sum+MESSAGE_LENGHT
let CHECKSUM=sum%256

let FILLCOUNTER=60-$MESSAGE_LENGHT
#echo "Message: $MESSAGE<br/>"
#echo "Length: $MESSAGE_LENGHT<br/>"
#echo "Counter: $FILLCOUNTER<br/>"
#echo "Sum: $sum<br/>"
#echo "Checksum: $CHECKSUM<br/>"

#fill the rest 50
for ((i=0; i<FILLCOUNTER; i++)); do
   printf '\x00' >> $TMP_FILE
done
chr "${CHECKSUM}" >> $TMP_FILE


cat $TAIL_FILE >> $TMP_FILE


#exit
#initialize
stty -F $LED_PORT ispeed $LED_PORT_SPEED ospeed $LED_PORT_SPEED cs8 ignbrk -brkint -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts

#wake up (just in case...)
printf '\x54' > $LED_PORT
printf '\x41' > $LED_PORT
printf '\x42' > $LED_PORT
printf '\x43' > $LED_PORT
printf '\x44' > $LED_PORT
printf '\x45' > $LED_PORT
sleep 3s
cat $TMP_FILE > $LED_PORT

if [ "$REQUEST_METHOD" == "GET" ]; then
 echo "<pre>";
fi

echo "Message: $MESSAGE"
echo "Effect: $EFFECT"
echo "Speed: $SPEED"
echo "OK"

if [ "$REQUEST_METHOD" == "GET" ]; then
 echo "</pre>";
 echo "<br/><a href='#' onClick='history.go(-1);'>Back</a>"
fi

fi
