#!/bin/sh

POWER_LOG="/tmp/power.log"
CHG_INFO="$(cat /sys/module/musb_hdrc/parameters/charger_info)"
KERN_INFO="$(uname -n|grep "aiv8167-rockman-emmc" 2>&1|wc -l)"
VARIANT="$(cat /etc/versions/variant)"
TARGET="$(cat /etc/versions/target)"



# copy app file
if [ -e /usr/sony/bin/sonyapp-copylink ]; then
  echo "SACL:" >>$POWER_LOG
  /usr/sony/bin/sonyapp-copylink 1>>$POWER_LOG 2>&1
fi

# thermal config
if [ -e /etc/thermal/thermal.conf -a -e /data/thermal ]; then
  cp /etc/thermal/thermal.conf /data/thermal/
  systemd stop thermal_manager.service
  systemd start thermal_manager.service
fi

# LED config
if [ x"$TARGET" = x"PVT" -o x"$TARGET" = x"MREL" ]; then
  if [ ! -e /etc/versions/DVT ]; then
    echo 1 > /sys/class/leds/green/brightness
    echo 1 > /sys/class/leds/red/brightness
    LED_CTRL="softled"
  fi
fi

echo "1st suspend" >>$POWER_LOG
if [ -e /etc/autostart ]; then
  att="$(cat /etc/autostart|tr -cd '0-9')"
  if [ x"$att" = x ]; then att=30; fi
  echo "autostart +$att" >>$POWER_LOG
  echo "+$att" > /sys/class/rtc/rtc0/wakealarm
fi

sync
echo mem > /sys/power/state

# usb otg
if [ "$CHG_INFO" -eq "3" ]; then
  echo "idle" > "/sys/devices/platform/mt_usb/swmode"
  sleep "0.3"
  echo "host" > "/sys/devices/platform/mt_usb/swmode"
  sleep "0.3"
fi

mount -o remount,rw /data
mount -o remount,rw /
mount --make-rshared /
systemctl disable syslog
rm -f "/data/syslog.log"
rm -f "/etc/autostart"
sync



# start weston if not
if ! systemctl status weston.service | grep -qE 'active\s+\(running\)'; then
  echo "start weston" >>$POWER_LOG
  systemctl start weston.service
fi

/usr/bin/cpu_mode full
/bin/power_manage usbreset rtcon safereboot $LED_CTRL 1>>$POWER_LOG 2>&1
