#!/bin/bash

# Copyright (C) 2007-2014 X2Go Project - http://wiki.x2go.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#
# Copyright (C) 2007-2014 Oleksandr Shneyder <oleksandr.shneyder@obviously-nice.de>
# Copyright (C) 2007-2014 Heinz-Markus Graesing <heinz-m.graesing@obviously-nice.de>

if [ $# -eq 1   ]; then
	SESSION_NAME="$1"
else 
	SESSION_NAME="$X2GO_SESSION"
fi

X2GO_LIB_PATH="$(x2gopath libexec)";

$X2GO_LIB_PATH/x2gosyslog "$0" "info" "$(basename $0) called with options: $@"

X2GO_AGENT_PID=`$X2GO_LIB_PATH/x2gogetagent "$SESSION_NAME"` 
X2GO_AGENT_PID=`echo "$X2GO_AGENT_PID"| awk {'print $1'}`

# workaround for knotify, keep silent in case no knotify is running
killall -HUP knotify &>/dev/null

# terminate x2godesktopsharing instance and remember that it was running...
x2gofeature X2GO_DESKTOPSHARING &>/dev/null && x2gosuspend-desktopsharing "$SESSION_NAME" || true

# run x2goserver-extensions for pre-suspend
x2gofeature X2GO_RUN_EXTENSIONS &>/dev/null && x2goserver-run-extensions "$SESSION_NAME" pre-suspend || true

kill -HUP $X2GO_AGENT_PID &>/dev/null && {
	$X2GO_LIB_PATH/x2gosyslog "$0" "notice" "session with ID $SESSION_NAME has been suspended successfully"

	# run x2goserver-extensions for post-suspend
	x2gofeature X2GO_RUN_EXTENSIONS &>/dev/null && x2goserver-run-extensions "$SESSION_NAME" post-suspend || true

	$X2GO_LIB_PATH/x2gochangestatus 'S' "$SESSION_NAME"  > /dev/null

} || {
	err_msg="ERROR: failed to suspend session with ID $SESSION_NAME"
	echo "$err_msg" 1>&2
	$X2GO_LIB_PATH/x2gosyslog "$0" "err" "$err_msg"

	# run x2goserver-extensions for fail-suspend
	x2gofeature X2GO_RUN_EXTENSIONS &>/dev/null && x2goserver-run-extensions "$SESSION_NAME" fail-suspend || true

	# If we reach here it means that the x2goagent process of the session has vanisshed
	# If this happens then we mark the session as finished...
	$X2GO_LIB_PATH/x2gochangestatus 'F' "$SESSION_NAME"  > /dev/null
}

export HOSTNAME
x2goumount-session "$SESSION_NAME"
