#!/bin/bash

DISPLAY_PORT="/dev/ttyAMA0"        # Serial port connected to display.

WIFI='wlan0'
ETH='eth0'

IFCONFIG='/sbin/ifconfig'
IWCONFIG='/sbin/iwconfig'
IWGETID='/sbin/iwgetid'

# Calculate Julian Day from year, month, #day.
daynum() {
    local year month day fctr

    if [ $# -ne 3 ]; then
        set `/bin/date "+%Y %m %d"`
    fi

    # Months come out with zero padded values, which will get interpreted as
    # octal numbers.  August & September, 08 & 09, are not valid octal numbers.
    # Prefix with 1 and subtract out the 100 to get around this issue.
    # year=$1 month=$(( 1$2 - 100 )) day=$(( 1$3 - 100 ))
    # Better(?) yet, remove any leading zeros.
    year=$1 month=${2#0} day=${3#0}

    fctr=$(( 365*year + day + 31*(month - 1) ))
    if [ $month -lt 3 ]; then
        year=$(( year-1 ))
        fctr=$(( fctr + year/4 - (year/100+1)*3/4 ))
    else
        fctr=$(( fctr - (month*4 + 23)/10 + (year/4) - ((year/100 + 1)*3/4) ))
    fi

    # Account for the above formula figuring that there's a year 0.  NOT!
    fctr=$(( fctr - 366 ))

    echo $fctr
}


# Calculate/display # of days until Christmas
christmas() {
    local d

    set $(/bin/date "+%Y")

    d=$(( $(daynum $1 12 25) - $(daynum) ))
    if [ $d -lt 0 ]; then
        d=$(( $1 + 1 ))
        d=$(( $(daynum $d 12 25) - $(daynum) ))
    fi

    if [ $d -eq 0 ]; then
        echo -e "\f       Merry\n     Christmas!"
    else
        echo -e "\f   Only $d-days\n  until Christmas!"
    fi
}


center_len() {
    local offset

    offset=$(( (20 - ${#1})/2 ))
    if [ $offset -lt 1 ]; then
       offset=0
    fi
    offset=$(( offset+${#1} ))
    echo $offset
}



title() {
    local lena lenb a b

    read model < /sys/firmware/devicetree/base/model

    if [ "$model" = "${model% Zero*}" -a \
 	 "$model" = "${model%[45]00 *}" ]; then
        a="${model% Model*}"
        b="Mo${model#*Mo}"
    else
        a="${model% Rev*}"
        b="Re${model#*Re}"
    fi

    lena=$(center_len "$a")
    lenb=$(center_len "$b")
    printf '\f%*s\r%*s' $lena "$a" $lenb "$b"
}


mywan() {
    local x
    # Need to make sure eth0* is available first.
    if $IFCONFIG | grep -q $ETH ; then
	x=$($IFCONFIG $ETH | grep 'inet ')
	if [ -z "$x" ] ; then
	    echo N/A
	else
	    set $x
	    echo ${2}
	fi
    else
	echo "N/A"
    fi
}


mywifi() {
    local x
    # Need to make sure eth0* is available first.
    if $IFCONFIG | grep -q $WIFI ; then
	x=$($IFCONFIG $WIFI | grep 'inet ')
        if [ -z "$x" ] ; then
	    echo N/A
        else
            set $x
            echo ${2}
    	fi
    else
        echo N/A
    fi
}


hostinfo() {
   echo -en "\f"
   echo "Host: $(hostname)"
   echo -n "WiFi:"
   mywifi
   sleep 5
   echo -n "WAN: "
   mywan
}


get_freq_pwr() {
    local ch pwr units x

    x="$($IWGETID -c $WIFI)"
    if [ -n "$x" ]; then
        set $x
        ch=${2#*:}
    else
        ch="N/A"
    fi

    x=$($IWCONFIG $WIFI | grep Tx-Power)
    if [ -n "$x" ]; then
        set $x
        pwr=${4#*=}
        units=$5
    else
        pwr="N/A"
        units=""
    fi
    echo -en "\fWiFi Channel: ${ch}\nTX Power: ${pwr} $units"
}

get_time() {
    local t len

    t=$(/bin/date "+%l:%M %p")
    t=${t#0}                        # Trim any leading zero from the hour
    len=$(center_len "$t")
    printf "%*s" $len "$t"
}


get_date() {
    local d len str

    set $(/bin/date "+%B %d, %Y")        # Alas, I cant do ${d/ 0/ } in ash.
    d=${2#0}
    str="$1 $d $3"
    len=$(center_len "$str")
    printf "%*s" $len "$str"
}


get_timedate() {
    local t d

    d=$(get_date)
    t=$(get_time)

    echo -en "\f$t\n$d"
}


up_load() {
    local x av
    x=$(uptime | sed -e 's/^.* up //' -e 's/, *[0-9]\+ user.*$//' -e 's/ \+/ /g')
    av=$(uptime | sed -e 's/^.*average: //' -e 's/,//g' )
    echo -en "\fLoad: $av\nUp: $x"
#    02:11:05 up 24 days,  1:31,  2 users,  load average: 0.18, 0.15, 0.10
}

cpu_temp() {
    local t

    read t < /sys/class/thermal/thermal_zone0/temp
    t=$(( ($t+50) / 100 ))
    printf "\fCPU Temp: %s.%s\016_\017C\n" ${t:: -1} ${t: -1:1}
}

show() {
    local i

    while true; do
        for i in title get_timedate hostinfo up_load get_freq_pwr cpu_temp christmas; do
            $i > $DISPLAY_PORT
            if [ $? -eq 0 ]; then
                sleep 7
            fi
        done
    done
}


show
