#!/bin/sh
# v1.3
# 2007 mbm at openwrt.org

while :
do {

  # wait for screen blank
  cd /sys/devices/platform/omapfb/panel
  while :
  do {
    echo wait
    sleep 10
    level=$(cat backlight_level) 
    tsd=$(cat /sys/bus/spi/devices/spi1.0/disable_ts)
    [ $level -eq 0 -a $tsd -eq 1 ] && break
  } done

  alarm=-1
  asleep=0

  # suspend
  while :
  do {
    # get current time
    cd /sys/devices/platform/retu-rtc
    : $((
      time=$(cat time),
      sec=time%256,
      time=time>>8&0xffff
    ))

    sleep 1

    # early wakeup condition
    [ $time -lt $alarm ] && break

    # set the alarm to wake us up
    printf "0x%04x\n" $((
      ext=sec>56,
      sec-=60*ext,
      time+=ext,
      min=(time%256)+1,
      hour=(time/256+min/60)%24,
      min%=60,
      sec=60-sec,
      asleep+=sec,
      alarm=hour*256+min
    )) > alarm
    echo 0 > alarm_expired

    # refresh the watchdog
    echo refresh
    echo 63 > /sys/devices/platform/retu-watchdog/period

    # and go to sleep
    echo sleep $sec
    echo standby > /sys/power/state
  } done

  # someone woke us up before the alarm
  : $((
    hour=asleep/(60*60),
    min=(asleep/60)%60,
    sec=asleep%60
  )) 

  printf "awake (asleep %d:%02d:%02d)\n" $hour $min $sec
} done
