#!/bin/bash
# Version easyVDR 0.4.3
# Kris 01.05.07
. /etc/vdr/sysconfig
. /etc/vdr/easyvdrshutdown.conf

TIMER=$1

if [ -z $WAKEUP_HOUR ]; then
  WAKEUP_HOUR=0
fi  

if [ $WAIT -lt 1 ]; then
  $WAIT="5"
fi   

USERS=$(who | wc -l)
if [ "$USERS" != "0" ] && [ "$IGNORE_USER" = "0" ]; then
  ERR_MSG="$USERS Benutzer sind angemeldet"
fi

for x in ${CMD_LST} ; do
  if pidof $x >/dev/null ; then
    ERR_MSG="$x laeuft"
  fi
done

for x in ${NET_LST} ; do
  if netstat -p | grep tcp | grep $x ; then
    ERR_MSG="User über $x angemeldet"
  fi
done

ASC_NEXT_TIMER=$(date -d "1970-01-01 UTC $TIMER seconds" +"%Y-%m-%d %R")

if [ $TIMER -gt 0 ] ; then
  NEXT_TIMER=$(($TIMER - $WAKEUP_RESERVE))
else
  NEXT_TIMER="0"
fi

NEXT_TIMER_SETTIME=$(date -d "1970-01-01 UTC $NEXT_TIMER seconds" +"%Y-%m-%d %H:%M:00")

hwclock -w --localtime

if [ "$ERR_MSG" = "" ] ; then
  case "$SHUTDOWNMETHOD" in
    ##############################################################################################
    "NVRAMWakeup")
      if [ "$NVRAM_IWNAME" = "" ]; then
        $NVRAMCMD -C /etc/nvram-wakeup.conf --directisa -ls $NEXT_TIMER
	NVRAM_STATUS=$PIPESTATUS
      else
        $NVRAMCMD -I $NVRAM_IWNAME --directisa -ls $NEXT_TIMER
	NVRAM_STATUS=$PIPESTATUS
      fi
      logger -s "Next nvram alarm at: $(date -d "1970-01-01 UTC $NEXT_TIMER seconds" +"%Y-%m-%d %R")"
      case $NVRAM_STATUS in
        0) # all went ok - new date and time set
	  EXITSTATUS=0
          poweroff
	  exit 0
        ;;
        1) # all went ok - new date and time set - reboot needed
	  EXITSTATUS=0
          case $BOOTLOADER in 
	    "lilo") 
              lilo -R PowerOff
              reboot
            ;;
	    "grub") 
              #grub-setdefault  
              echo "grub"
	    ;;
	  esac
	  exit 0
        ;;
        2) # something went wrong
          ERR_MSG="Die Systemzeit kann icht gestellt werden"
	  EXITSTATUS=1
          $SVDRPCMD MESG "$ERR_MSG" &
          logger -s "$ERR_MSG"
          poweroff
          exit 1
        ;;
      esac
    ;;
    ##############################################################################################
    "Settimer")
      #### Ohne Timer einfach "Poweroff" #####
      if [ $TIMER -eq 0 ]; then
        ERR_MSG="Kein Timer gesetzt"
        $SVDRPCMD MESG "$ERR_MSG" &
        logger -s "$ERR_MSG"
        poweroff
        exit 1
      fi
      # Aufwachzeit in Sekunden seit Epoch umrechnen
      Wakeup=`date -d "$NEXT_TIMER_SETTIME" +%s`
      if [ "$?" -eq "1" ]; then
        ERR_MSG="kein oder falsches Datumsformat"
        $SVDRPCMD MESG "$ERR_MSG - Shutdown abgebrochen" &
        logger -s "$ERR_MSG"
        exit 1
      fi   
      Now=`date +%s`
      Bios=`date -u -d "${BiosWakeup}" +%s`
         
      if [ "${Wakeup}" -lt "${Now}" ]; then    
        echo "Aufwachzeit ist in der Vergangenheit"
        ERR_MSG="Aufwachzeit ist in der Vergangenheit"
        $SVDRPCMD MESG "$ERR_MSG - Shutdown abgebrochen" &
        logger -s "$ERR_MSG"
        exit 1
      fi  
      # Zeitdifferenz zwischen Wakeup und aktueller Zeit in Sekunden ausrechnen
      Diff=$[${Wakeup}-${Now}]
      # Zeitdifferenz zwischen BiosWakeup und jetzt in Sekunden in Datei speichern
      echo "$[${Now}-${Bios}+${Diff}]" > /etc/timediff
      # Uhr zurück stellen
      date -s "${BiosWakeup} ${Diff} seconds ago" >/dev/null
      if [ "$?" -gt "0" ]; then
        echo "Die Systemzeit kann icht gestellt werden - als root angemeldet ?"
        ERR_MSG="Die Systemzeit kann icht gestellt werden - als root angemeldet ?"
        $SVDRPCMD MESG "$ERR_MSG - Shutdown abgebrochen" &
        logger -s "$ERR_MSG"
        exit 1
      fi
      # CMOS-Uhr aktualisieren
      /etc/init.d/Runvdr stop
      hwclock -w --localtime
      poweroff
      exit 0
    ;;
    ##############################################################################################
    "ACPI")
	if [ -f $PROC_ALARM ] ; then
        DAY_AHEAD=$(date -d "1 day" +%s)
        if [ $NEXT_TIMER -gt $DAY_AHEAD ] || [ "$TIMER" = "0" ] ; then
          ACT_HOUR=$(date +%k)
          if [ $WAKEUP_HOUR -gt $ACT_HOUR ] ; then
	    NEXT_ALARM=$(date -d "$WAKEUP_HOUR:00" +"%Y-%m-%d %R")
          else
            NEXT_ALARM=$(date -d "$WAKEUP_HOUR:00 1 day" +"%Y-%m-%d %R")
          fi
        else
          NEXT_ALARM=$(date -d "1970-01-01 UTC $NEXT_TIMER seconds" +"%Y-%m-%d %R")
        fi
        if [ "$TIMER" != "0" ] ; then
          logger -s "Next acpi alarm at: $NEXT_ALARM"
          NT=$(date -d "$NEXT_ALARM" +"%Y%m%d%H%M")
          echo -n "$NEXT_ALARM" > $PROC_ALARM
          sleep 2
          echo -n "$NEXT_ALARM" > $PROC_ALARM
        else
          logger -s "No timer set"
        fi
      else
        logger -s "No wakeup possible - shutting down anyway"
      fi
    poweroff
    exit 0
    ;;
    ##############################################################################################
    "extb")
      /usr/bin/extb-poweroff.pl $NEXT_TIMER
    ;;
    ##############################################################################################
    "JepsenHWWakeup")
      if [ -e /etc/vdr/vdr-addon-hw-wakeup.conf ]; then
        . /etc/vdr/vdr-addon-hw-wakeup.conf
      fi
    
      # Defaults:
      [ -z "$ENABLED" ]           && export ENABLED="no"
      [ -z "$WAKEUP_PORT" ]       && export WAKEUP_PORT="/dev/ttyS0"
      [ -z "$KILL_LIRC" ]         && export KILL_LIRC="no"
      [ -z "$KILL_LCDD" ]         && export KILL_LCDD="yes"
      [ -z "$MIN_PRE_TIMER" ]     && export MIN_PRE_TIMER=5
      [ -z "$MAX_POWEROFF_TIME" ] && export MAX_POWEROFF_TIME=0
      [ -z "$MAX_TRY_AGAIN" ]     && export MAX_TRY_AGAIN=0
    
      # Const
      NEVER=2147483647
    
      if [ $MAX_TRY_AGAIN -gt 0 ]; then
        # another script wants to retry shutdown later
        ERR_MSG="Shutdown abgebrochen"
        $SVDRPCMD MESG "$ERR_MSG" &
	logger -s vdr-addon-hw-wakeup "$ERR_MSG - Sutdown abgebrochen"
        EXITCODE=0
      else
        if [ $ENABLED = "no" ]; then
          # vdr-addon-hw-wakeup is disabled, so just exit
          ERR_MSG="hw-wakeup functionality is disabled"
          $SVDRPCMD MESG "$ERR_MSG - Shutdown abgebrochen" &
	  logger -s vdr-addon-hw-wakeup "$ERR_MSG - Sutdown abgebrochen"
          logger -t vdr-addon-hw-wakeup "hw-wakeup functionality is disabled"
          EXITCODE=0
        else
        # calculate, at what time the machine should be powered on
        # VDR-Timer
        NOW=$((`date +%s`))
        #    echo "NOW           " `date -d "1970-01-01 $NOW seconds UTC" "+%H:%M %d.%m.%Y"` $NOW
        if [ -z $TIMER ] || [ $TIMER -eq 0 ]; then
          NEXTTIMER=$NEVER
        else
          NEXTTIMER=`expr $TIMER - $MIN_PRE_TIMER \* 60`
        fi
        #    echo "TIMER         " `date -d "1970-01-01 $NEXTTIMER seconds UTC" "+%H:%M %d.%m.%Y"` $NEXTTIMER
        # Daily Timer
        if [ -z $DAILY_TIMER_STD ] || [ -z $DAILY_TIMER_MIN ]; then
          NEXTDAILYTIMER=$NEVER
        else
          NEXTDAILYTIMER=`date +"%d %b %Y"`
          NEXTDAILYTIMER=`date -d "$NEXTDAILYTIMER $DAILY_TIMER_STD:$DAILY_TIMER_MIN" +%s`
          if [ $NOW -gt $NEXTDAILYTIMER ]; then
            NEXTDAILYTIMER=`expr $NEXTDAILYTIMER + 86400`
          fi
        fi
        #    echo "DAILYTIMER    " `date -d "1970-01-01 $NEXTDAILYTIMER seconds UTC" "+%H:%M %d.%m.%Y"` $NEXTDAILYTIMER
        # MaxPowerOff Time
        if [ $MAX_POWEROFF_TIME -eq 0 ]; then
          WAKEUPTIME=$NEVER
        else
          WAKEUPTIME=`expr $NOW + $MAX_POWEROFF_TIME \* 60`
        fi
        #    echo "MAXPOWEROFF   " `date -d "1970-01-01 $WAKEUPTIME seconds UTC" "+%H:%M %d.%m.%Y"` $WAKEUPTIME
        # Who comes first?
        if [ $WAKEUPTIME -gt $NEXTTIMER ] && [ $NEXTDAILYTIMER -gt $NEXTTIMER ]; then
          WAKEUPTIME=$NEXTTIMER
        else
          if [ $WAKEUPTIME -gt $NEXTDAILYTIMER ]; then
            WAKEUPTIME=$NEXTDAILYTIMER
          fi
        fi
        #    echo "WAKEUPTIME    " `date -d "1970-01-01 $WAKEUPTIME seconds UTC" "+%H:%M %d.%m.%Y"` $WAKEUPTIME    
        if [ $WAKEUPTIME -eq $NEVER ]; then
          WAKEUPSTR=""
        else
          WAKEUPSTR=`date -d "1970-01-01 $WAKEUPTIME seconds UTC" +%H%M%d%m`
        fi
    
        TIMESTR=`date +%H%M%S%d%m%y%w`
    
    	# Kill LIRC
        if [ $KILL_LIRC = "yes" ]
        then
          logger -t vdr-addon-hw-wakeup "Starting Module 8250"
          killall lircd
          sleep 2
          modprobe -r lirc_serial
          sleep 4
          modprobe 8250
          setserial $WAKEUP_PORT uart 16550A
          sleep 8
        fi
    
        # Kill LCDd
        if [ $KILL_LCDD = "yes" ]; then
          killall LCDd
          sleep 1
          echo -n -e "\317" > $WAKEUP_PORT
        fi
        
        logger -t vdr-addon-hw-wakeup "echo ATS$WAKEUPSTR > $WAKEUP_PORT"
        echo ATS$WAKEUPSTR > $WAKEUP_PORT
        logger -t vdr-addon-hw-wakeup "echo RTS$TIMESTR > $WAKEUP_PORT"
        echo RTS$TIMESTR > $WAKEUP_PORT
        EXITCODE=0
        poweroff
      fi
    fi
    ;;
    ##############################################################################################
    "kein")
      poweroff
    ;;
  esac
else
  $SVDRPCMD MESG "$ERR_MSG - Shutdown abgebrochen" &
  logger -s "$ERR_MSG - Sutdown abgebrochen"
  echo "$SVDRPCMD HITK power &" | at now +$WAIT minute
  sleep 2
  exit 1
fi
exit 0