#!/bin/bash
# -*- Mode: shell-script -*-
# Copyright (C) 2003-2006 by Mandriva
# Author: Chmouel Boudjnah
# Redistribution of this file is permitted under the terms of the GNU 
# Public License (GPL)
#
# suspend: 50
# resume: 5

. /etc/sysconfig/suspend

STATE=/var/run/pm/vbestate
OLDVT=/var/run/pm/oldvt

ARG=$1
MOD=$2

function get_x_pid {
    # X process may be called either Xorg or X
    pid=$(pidof Xorg)
    if [ -z "$pid" ]; then
	pid=$(pidof X)
    fi
}

function suspend {
    get_x_pid
    if [[ ( -n "$CHANGE_VT" || "$VBESTATESAVE" = "yes" || "$VBEAUTO" = "yes" ) && -n "$pid" ]];then
	fgconsole > $OLDVT
	chvt 1
	kill -STOP $pid
    fi
    if [[ "$MOD" = "s3" && "$VBESTATESAVE" = "yes" ]];then
	echo "Saving VBE state"
	/usr/sbin/vbetool vbestate save > $STATE
    fi
    if [[ "$MOD" = "s3" && "$VBEAUTO" = "yes" ]];then
 	/usr/sbin/wltool --quiet --suspend $WLTOOL_SUSPEND
    fi
}

function resume {
    if [[ "$MOD" = "s3" ]];then
	if [[ "$VBEPOST" = "yes" ]];then
	    echo "Running VBE Post"
	    /usr/sbin/vbetool post
	fi
	if [[ "$VBESTATESAVE" = "yes" && -f $STATE ]];then
	    echo "Restoring VBE state"
	    /usr/sbin/vbetool vbestate restore < $STATE
	    rm -f $STATE
	fi
	if [[ "$VBEAUTO" = "yes" ]]; then
	    /usr/sbin/wltool --quiet --resume $WLTOOL_RESUME
	fi
    fi

    get_x_pid
    if [[ -n "$CHANGE_VT"  && -n "$pid" ]];then
	kill -CONT $pid
	if [[ "$CHANGE_VT" != "0"  ]]; then
	    chvt "$CHANGE_VT"
	else
	    chvt "$(cat $OLDVT)"
	fi
    fi
}

case $ARG in
    suspend)
	suspend
	;;
    resume)
	resume
	;;
esac
