#!/bin/sh
# Stop all init scripts in /etc/init.d
# executing them in reversed numerical order.
cp -fr /var/cache/samba /xvar/cache/
buzzer_config=/etc/buzzer/buzzer_config.info
if [ -e $buzzer_config ]; then
    status=$(iniparse  -c -f /etc/buzzer/buzzer_config.info  -k  system_shutdown  $buzzer_config)
    if [ "$status" != '' ] && [ "$status" -eq '1' ]; then
        buzzer all 1 6
    fi
else
    buzzer all 1 6
fi
hookpid=$(pidof restart_service)
if [ ! -z "$hookpid" ]; then
    kill $hookpid
fi
# check & stop service safely
service allboot stop
# exec power on for timer
/etc/tos/scripts/powertimer &

for i in $(ls -r /etc/init.d/S[0-9]*); do
    # Ignore dangling symlinks (if any).
    [ ! -f "$i" ] && continue
    echo $i | grep ".en$" >/dev/null
    [ $? -eq 0 ] && continue
    case "$i" in
    *.sh)
        # Source shell script for speed.
        (
            trap - INT QUIT TSTP
            set stop
            . $i
        )
        ;;
    *)
        # No sh extension, so fork subprocess.
        $i stop
        ;;
    esac
done
service tosdaemon stop
service redis stop &
# for wake on lan
[ -x /etc/tos/scripts/wakeonlan ] && /etc/tos/scripts/wakeonlan &
wait
/etc/init.d/msg stop

sync
umount /home >/dev/null 2>&1
umount /Volume*/@usb/* >/dev/null 2>&1
umount /Volume*/@iso/* >/dev/null 2>&1
umount /Volume*/@iscsi/* >/dev/null 2>&1
df-json | awk '/\/Volume[0-9]+\/./' | while read line; do
    mntpath=$(echo $line | awk '{print $8}')
    umount $mntpath
done
df-json | awk '/\/Volume[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 mddev in /dev/md[0-9]*; do
    if [ "$mddev" = "/dev/md8" -o "$mddev" = "/dev/md9" ]; then
        continue
    fi
    mdadm -S $mddev
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
