#!/bin/sh
# tlp - disable Ultrabay on resume if it was disabled on the preceding suspend
#
# Copyright (c) 2013 Thomas Koch <linrunner at gmx.net>
# This software is licensed under the GPL v2 or later.

. "${PM_FUNCTIONS}"

readonly LIBDIRS="/usr/lib/tlp-pm /usr/lib64/tlp-pm"
readonly LIBS="tlp-functions"
readonly STATE=tp_bay_off

get_bay () {
	dock=$(grep -l ata_bay /sys/devices/platform/dock.?/type)
	dock=${dock%%/type}
	if [ ! -d "$dock" ]; then
		dock=""
	fi
}

suspend_bay () {
	get_bay
	if [ -n "$dock" ]; then
		if [ -e $dock/docked ]; then
			if [ "$(cat $dock/docked)" = "0" ]; then
				savestate $STATE 1
				echo_debug "pm" "49bay.suspend: bay=off"
			else
				echo_debug "pm" "49bay.suspend: bay=on"
			fi
		fi
	fi
}

resume_bay () {
	local cnt
	local rc
	
	state_exists $STATE || return
	[ "$(restorestate $STATE)" = "1" ] || return
		
	get_bay
	if [ -n "$dock" ]; then
		if [ -e $dock/undock ]; then
			cnt=5
			rc=1
			until [ $rc = 0 -o $cnt = 0 ]; do
				cnt=$((cnt - 1))
				echo 1 > $dock/undock
				rc=$?
				[ $rc = 0 ] || sleep 0.5
			done
			echo_debug "pm" "49bay.resume_bayoff: rc=$rc"
			return 0
		fi
	fi
}

for libdir in $LIBDIRS; do [ -d $libdir ] && break; done
[ -d $libdir ] || exit 0

for lib in $LIBS; do 
    [ -f $libdir/$lib ] || exit 0
    . $libdir/$lib
done

read_defaults || exit 0

[ "$TLP_ENABLE" = "1" ] && [ "$BAY_POWEROFF_ON_BAT" = "1" ] || exit 0

echo_debug "pm" "49bay.$1"

# MAIN
case $1 in
	hibernate|suspend)
		suspend_bay
		;;
		
	thaw|resume)
		resume_bay
		;;
		
	*) exit $NA
		;;
esac

exit 0

