#!/bin/dash
# originally by shinobar 28sep09
# re-written by jamesbond, 2013

#Debounce switch 
[ -e /tmp/acpi_poweroff ] && exit
touch /tmp/acpi_poweroff #acpi_poweroff-delay.sh called later will delete this flag after a delay.
acpi_poweroff-delay.sh & 

### config
AUFS_ROOT=/aufs
STOP_USB=	# STOP_USB=y if we want to stop it 
[ -e $BOOTSTATE_PATH ] && . $BOOTSTATE_PATH # AUFS_ROOT

######### helpers ##########

# replaces probedisk2 used earlier
# stdout: list of usb drives, without /dev
get_usb_drives() {
	for p in $(ls /sys/class/block | grep -Ev "^nbd|^loop|^ram"); do
		pp=$(readlink /sys/class/block/$p)
		case $pp in *usb*) echo $p ;; esac
	done
}

# $@ - devices (without /dev)
# stdout: mountpoints for devices (if any)
get_mount_points() {
	[ -z "$1" ] && return
	pp=""
	for p; do pp="$pp||/^\/dev\/$p/"; done
	pp=${pp#||}
	awk "$pp {print \$2}" /proc/mounts
}

########### main ###########

# make sure no data loss
sync

# don't suspend when lid is open
#grep -q open /proc/acpi/button/lid/*/state && exit

# don't suspend while we're shutting down
for p in acpi_poweroff.sh wmpoweroff poweroff rc.shutdown rc.cleanup; do
	pidof $p > /dev/null && exit
done

# umount all usb media, then stop usb driver - if asked
if [ $STOP_USB ]; then
	for p in $(get_mount_points $(get_usb_drives)); do
		case "$p" in ${AUFS_ROOT}/*) exit ;; esac # abort if in-use by system
		fuser -mk $p
		umount $p
	done
	rmmod ehci_hcd
fi

# stop networking
/etc/rc.d/rc.network stop
kill -9 $(pidof wpa_cli)
killall dhcpcd-wpagui
killall dhcpcd
killall wpa_supplicant

#suspend
echo mem > /sys/power/state 

# wakeup - restart network
modprobe ehci_hcd
/etc/rc.d/rc.network
/etc/init.d/50-Wpagui start


