#! /usr/bin/env python
#
#    byobu-select-session
#    Copyright (C) 2010 Canonical Ltd.
#
#    Authors: Dustin Kirkland <kirkland@ubuntu.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")
HOME=os.getenv("HOME")
BYOBU_CONFIG_DIR=os.getenv("BYOBU_CONFIG_DIR", HOME+"/.byobu")
BYOBU_BACKEND=os.getenv("BYOBU_BACKEND", "screen")
choice = ""
sessions = []
text = []
i = 0

output = commands.getoutput('%s -ls ' % BYOBU_BACKEND)
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("Select %s" % s.strip())
			items = s.split(" ")
			sessions.append(items[1])
			i += 1

show_shell = os.path.exists("%s/.always-select" % (BYOBU_CONFIG_DIR))
if i>1 or show_shell:
	sessions.append("NEW")
	text.append("Create a new Byobu session")
	sessions.append("SHELL")
	text.append("Run a shell without Byobu (%s)" % SHELL)

if len(sessions) > 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
		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");
elif len(sessions) == 1:
 	# Attach to the chosen session; must use the binary, not the wrapper!
	os.execvp(BYOBU_BACKEND, ["", "-AOxRR"])

if choice:
	if sessions[choice-1] == "NEW":
		# Create a new session
		os.execvp("byobu", ["", SHELL])
	elif sessions[choice-1] == "SHELL":
		os.execvp(SHELL, [SHELL])
	else:
	 	# Attach to the chosen session; must use the binary, not the wrapper!
		os.execvp(BYOBU_BACKEND, ["", "-AOxRR", sessions[choice-1]])

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