#!/bin/bash

# This is the PowerPC version of PMI.

# (C) 2006 Martin Pitt <martin.pitt@ubuntu.com>

command="$1"
event="$2"

usage () {
        echo "Usage: $0 query|action <event>" >&2
        echo "       $0 capabilities" >&2
        exit 254
}

query () {
        [ ! -z "$1" ] && event="$1"
        case "$event" in
                suspend|sleep)
			perl << EOF
sub PMU_IOC_CAN_SLEEP { 0x40044205; }
open PMU, '/dev/pmu' or die "open /dev/pmu: \$!";
\$p = pack 'l', 0;
ioctl PMU, &PMU_IOC_CAN_SLEEP, \$p or die "ioctl: \$!";
(\$v) = unpack 'l', \$p;
exit (\$v ? 0 : 1);
EOF
			result=$?
                ;;
		hibernate)
			# no hibernation support at the moment
			result=1
		;;
                *)
                        result=1
                        echo "No such event found" >&2
                ;;
        esac
}

call_scripts() {
    if [ -x /etc/apm/apmd_proxy ]; then
	/etc/apm/apmd_proxy $1 $2
    else
	run-parts --arg=$1 --arg=$2 /etc/apm/event.d
	if [ -d /etc/apm/$1.d ]; then
	    run-parts --arg=$1 --arg=$2 /etc/apm/$1.d
	fi
    fi
}
                        
run () {
	case "$1" in
		suspend|sleep)
			# call suspend scripts
			call_scripts suspend user

			# trigger sleep
			perl <<EOF
sub PMU_IOC_SLEEP { 0x20004200; }
open PMU, "/dev/pmu" or die "open /dev/pmu: \$!";
ioctl PMU, &PMU_IOC_SLEEP, 0;
EOF

			# call resume scripts
			call_scripts resume suspend
		;;
		hibernate)
			echo 'Not implemented' >&2
		;;
                *)
                        echo "No such event found" >&2
                ;;
	esac
}
                
capabilities () {
        for i in "hibernate" "suspend"; do 
                query $i 
                [ "$result" -eq 0 ] && caps="$caps $i"
        done
        echo $caps
}
        
case "$command" in
        query)
                query $event
                exit $result
                ;;
        action)
                run $event
                ;;
        capabilities)
                capabilities
                ;;
        *)
                usage
                ;;
esac

exit 0
