#!/bin/sh
# Stop all init scripts in /etc/init.d
# executing them in reversed numerical order.
# for wake on lan
buzzer_config=/etc/buzzer/buzzer_config.info
if [ -e $buzzer_config ]; then
  status=$(awk -F '=' '/''/{a=1}a==1&&$1~/'system_shutdown'/{print $2;exit}' $buzzer_config)
  if [ "$status" != '' ] && [ "$status" -eq '1' ]; then
    ledtest 12 0
    sleep 1
    ledtest 12 1
  fi
else
  ledtest 12 0
  sleep 1
  ledtest 12 1
fi

if [ -x /etc/tos/scripts/wakeonlan ]; then
  /etc/tos/scripts/wakeonlan
fi

sync
umount /home >/dev/null 2>&1
umount /mnt/usb/* >/dev/null 2>&1
umount /mnt/iso/* >/dev/null 2>&1
umount /mnt/iscsi/* >/dev/null 2>&1
df-json | awk '/\/mnt\/md[0-9]+\/./' | while read line; do
  mntpath=$(echo $line | awk '{print $8}')
  umount $mntpath
done
df-json | awk '/\/mnt\/md[0-9]+$/' | while read line; do
  fs=$(echo $line | awk '{print $2}')
  mntpath=$(echo $line | awk '{print $8}')
  if [ "$fs" = "btrfs" ]; then
    btrfs filesystem sync $mntpath
  else
    sync
  fi
  #wait for sync to disks
  sleep 1
  umount $mntpath
done

# stop the raid by command
vgchange -an 2>/dev/null
for blk in $(ls /dev/md[0-9]*); do
  if [ "$blk" = "/dev/md8" -o "$blk" = "/dev/md9" ]; then
    continue
  fi
  mdadm -S $blk
done

# let disk to standby
for blk in $(ls /dev/sd[a-z] 2>/dev/null); do
  hdparm -Y $blk
done
for blk in $(ls /dev/sd[a-z][a-z] 2>/dev/null); do
  hdparm -Y $blk
done
# wait disk for standby
sleep 5
