#!/bin/sh
# Stop all init scripts in /etc/init.d
# executing them in reversed numerical order.
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
        buzzer all 1 6
    fi
else
    buzzer all 1 6
fi
# cache for samba domain
cp -rf /var/cache/samba /xvar/cache/
# exec power on for timer
/etc/tos/scripts/powertimer
/etc/init.d/msg stop

# check & stop service safely
checkServiceStop() {
    local shell_script=$1
    local total=10
    cat $shell_script | grep "status)" >/dev/null
    is_status=$?
    while [ $total -gt 0 ]; do
        $shell_script stop
        sleep 1
        if [ $is_status -eq 0 ]; then
            $shell_script status | grep "stopped" >/dev/null
            [ $? -eq 0 ] && break
        elif [ $total -eq 8 ]; then
            break
        fi
        let total=total-1
    done
}

# stop for application
for item in $(ls -r /etc/sc.d/*); do
    shell_name=$(basename $item)
    shell_script=/etc/init.d/$shell_name
    [ ! -x $shell_script ] && continue
    checkServiceStop $shell_script
done

for i in $(ls -r /etc/init.d/S??*); 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
/etc/init.d/redis stop
# for wake on lan
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 2
    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
