#!/bin/sh
# sed -i "s/LEDPatterns=/LEDPatterns=PatternVboost;/" /etc/mce/mce.ini
# vboost with reset on exit and (#'d) partial hostmode for PF-kernel
#(c) 20120520 J.Reisenweber

set -eu
true=true
false=""

${debug=/bin/false} && set -vx; # call like ~# debug="echo -n $0; date" script.sh

#const
PatternVboost=PatternVboost
dbussend="/usr/bin/run-standalone.sh /usr/bin/dbus-send"
PATH=$PATH:/usr/local/sbin:/sbin:/usr/sbin

#var
: ${start_bme=$true}
: ${notify=$true}



trap cleanup INT QUIT TERM EXIT
cleanup(){
  trap - INT QUIT TERM EXIT

  # reset bq24150
  i2cset -y -m 0x80 2 0x6b 0x04 0x80

  # stop LED indicator 
  $dbussend --system --type=method_call \
    --dest=com.nokia.mce /com/nokia/mce/request \
    com.nokia.mce.request.req_led_pattern_deactivate \
    string:$PatternVboost

  $debug && (
    Reg1=`i2cget -y 2 0x6b 0x00`
    echo $Reg1
  )
  
  if [ $start_bme ]
  then
    sleep 2
    log "Starting bme"
    /sbin/start --quiet bme
  fi
  exit
}

log(){
  echo "${0}: $@"
}

logn(){
  echo -n "${0}: $@"
}

# the script body. We read in whole text, and then execute a main at end of script,
# this ensures the whole script has correct syntax and there'll be no reads at 
# runtime
main(){
  log "Stopping bme"
  # only start bme at end of script if it was stopped by us
  /sbin/stop bme 2>&1 | grep -q "bme (stop) killed" || start_bme=$false
  sleep 3
  #echo host >mode
  
  # start vbus boost 5V
  i2cset -y -m 0x07 2 0x6b 0x01 0x05;
  
  # set notification LED
  $dbussend --system --type=method_call \
    --dest=com.nokia.mce /com/nokia/mce/request \
    com.nokia.mce.request.req_led_pattern_activate \
    string:$PatternVboost
  
  #sleep 1
  #echo F >/proc/driver/musb-hdrc

  while sleep 5; do
    Reg1=`i2cget -y 2 0x6b 0x00`
    if [ 8 -ne $(( Reg1 & 0x0F )) ]; then
      errortext1="ERROR in VBUS supply: BQ24150-Reg1=$Reg1"
      case $(( Reg1 & 0x07)) in
        0) errortext2="No error, just stopped";;
        1) errortext2="VBUS OVERVOLTAGE - You just fried your N900";;
        2) errortext2="OVERLOAD - N900 can deliver max 200mA. VBUS got shut off";;
        3) errortext2="Battery too low. VBUS shut off";;
        4) errortext2="Battery OVP - WTF are you doing?";;
        5) errortext2="Thermal Shutdown (too hot)";;
        6) errortext2="Watchdog expired. Script sucks";;
        *) errortext2="WTF? This should not happen";;
      esac

      log "$errortext1"
      log "$errortext2"
      if [ $notify ]; then
        $dbussend --type=method_call --dest=org.freedesktop.Notifications \
         /org/freedesktop/Notifications \
         org.freedesktop.Notifications.SystemNoteDialog \
         string:"`echo -en "Shutting down 5V supply for USB! Reason:\n$errortext2"`" uint32:0 string:"WARN"; #no idea about WARN
      fi
      cleanup
    fi
    
    # tickle watchdog timer
    i2cset -y -m 0x80 2 0x6b 0x00 0x80;
  done
  cleanup
}
main "$@"; exit