#! /usr/bin/env python
#
#    byobu-select-session
#    Copyright (C) 2010 Canonical Ltd.
#
#    Authors: Dustin Kirkland <kirkland@canonical.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 3 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, see <http://www.gnu.org/licenses/>.


import commands, os, re, sys

PKG = "byobu"
SHELL = os.getenv("SHELL", "/bin/bash")
choice = ""
sessions = []
text = []
i = 0
output = commands.getoutput('screen -ls ')
if output:
	for s in output.split("\n"):
		s = re.sub(r'\s+', ' ', s)
		# Ignore hidden sessions (named sessions that start with a ".")
		if s.find(" ") == 0 and len(s) > 1 and s.count("..") == 0:
			text.append(s)
			items = s.split(" ")
			sessions.append(items[1])
			i += 1

if i > 1:
	sys.stdout.write("\nByobu sessions...\n\n")
	tries = 0
	while tries < 3:
		i = 1
		for s in text:
			sys.stdout.write("  %d. %s\n" % (i, s))
			i += 1
		sys.stdout.write("  %d.  Create a new session\n" % i)
		i += 1
		try:
			choice = input("\nChoose 1-%d [1]: " % (i-1))
			if choice >= 1 and choice < i:
				break
			else:
				tries += 1
				choice = ""
				sys.stderr.write("\nERROR: Invalid input\n");
		except KeyboardInterrupt:
			print
			sys.exit(0)
		except:
			if choice == "":
				choice = 1
				break
			tries += 1
			choice = ""
			sys.stderr.write("\nERROR: Invalid input\n");

if choice:
	if choice == i-1:
		# Create a new session
		os.execvp("byobu", ["", SHELL])
	else:
	 	# Attach to the chosen session; must use the 'screen' binary
		os.execvp("screen", ["", "-AOxRR", sessions[choice-1]])

# No valid selection, default to the youngest session, create if necessary
os.execvp("byobu", ["", "-AOxRR"])
