#! /usr/bin/env python3
# -*- coding: utf-8 -*-

# Copyright (C) 2015 Inuvika Inc.
# http://www.inuvika.com
#
# Copyright (C) 2012 Ulteo SAS
# http://www.ulteo.com
# Author David LECHEVALIER <david@ulteo.com>
#
# 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; version 2
# of the License
#
# 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 Street, Fifth Floor, Boston, MA  02110-1301, USA.

import os
import re
import sys
import xrdp
from xrdp import XrdpException


def disconnect():
	display = os.getenv("DISPLAY")
	if display is None:
		print("Your Session is not valid", file=sys.stderr)
		sys.exit(1)

	regexp = re.compile("^\:(\d*)\.(\d*)$")
	result = regexp.match(display)
	if result is None:
		print("Your Session environment is invalid", file=sys.stderr)
		sys.exit(1)

	session_id = result.group(1)

	try:
		xrdp.SessionDisconnect(session_id)
	except XrdpException:
		print("Failed to perform the action", file=sys.stderr)


if __name__ == '__main__':
	disconnect()
