#!/bin/bash
#
# screenselector.sh						7 Oct 2005
#
# (GPL) Marno van der Molen - marno.vandermolen@gmail.com
#
# Usage 
# -----
# This script checks how many screens there are (max of 4) and
# then prints a menu to choose which one you want to go to.
#
# Can also be ran with an option like: screenselector 1
# which then goes to screen 1.
#
# When ran without an option, and only one screen present, it will 
# automatically go to that screen.
#
# When ran with the option 'n' it will automatically create a new screen
# for you and you will be in that screen when the command is done.
#
GOTO=$1
ARGS=0

if [ $1 = "n" ] > /dev/null 2>&1
then
	screen -q
	exit
fi

if [ $1 ] > /dev/null 2>&1
then
	ARGS=1
fi

TOTAL="`screen -ls | grep -c "Detached"`"

if [ $TOTAL -eq 0 ]
then
	echo "There are no screens to be resumed!"
	exit
fi

if [ $TOTAL -eq 1 ]
then
	echo "There is only 1 screen to resume!"
	sleep 0.5s
	GOTO=1
	ARGS=1
fi

if [ $GOTO -gt $TOTAL ] > /dev/null 2>&1
then
	echo "That screen does not exist!"
	exit
fi

clear

if [ $TOTAL -gt 0 ]
then
	OPTION1=`screen -ls | grep -i "Detached" | awk {' print $1'} | head -n 1`
fi
if [ $TOTAL -gt 1 ]
then
	OPTION2=`screen -ls | grep -i "Detached" | awk {' print $1'} | head -n 2 | tail -n 1`
fi
if [ $TOTAL -gt 2 ]
then
	OPTION3=`screen -ls | grep -i "Detached" | awk {' print $1'} | head -n 3 | tail -n 1`
fi
if [ $TOTAL -gt 3 ]
then
	OPTION4=`screen -ls | grep -i "Detached" | awk {' print $1'} | head -n 4 | tail -n 1`
fi

if [ $ARGS -eq "1" ] > /dev/null 2>&1
then
	if [ $GOTO -eq 1 ]
	then
		screen -r $OPTION1
		exit
	fi

	if [ $GOTO -eq 2 ]
	then
		screen -r $OPTION2
		exit
	fi
	
	if [ $GOTO -eq 3 ]
	then
		screen -r $OPTION3
		exit
	fi
	
	if [ $GOTO -eq 4 ]
	then
		screen -r $OPTION4
		exit
	fi
fi

echo "Screen Shells Available"
echo "------ ------ ---------"
echo
echo "Choose one of the following shells:"
echo
if [ $TOTAL -gt 0 ]
then
	echo "[1] - $OPTION1"
fi
if [ $TOTAL -gt 1 ]
then
	echo "[2] - $OPTION2"
fi
if [ $TOTAL -gt 2 ]
then
	echo "[3] - $OPTION3"
fi
if [ $TOTAL -gt 3 ]
then
	echo "[4] - $OPTION4"
fi
echo

echo -n "Going to shell #: "
if [ $ARGS -ne "0" ]
then
INPUT=$GOTO
else
read INPUT
fi

case "$INPUT" in
	"1" )
	screen -r $OPTION1
	;;
	"2" )
	screen -r $OPTION2
	;;
	"3" )
	screen -r $OPTION3
	;;
	"4" )
	screen -r $OPTION4
	;;
	"Q" | "q" )
	exit
	;;
esac

