#!/bin/sh -e
###############################################################################
#    screenbin
#      This script is inspired by the concept of a 'pastebin', implementing
#      a shared screen evironment using EC2.
#
#    Copyright (C) 2008 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/>.
###############################################################################


error() {
	echo "Error: $1"
	exit 1
}

usage() {
	echo
	echo "Usage:"
	echo
	echo "  screenbin [--rw] [--ec2-keypair FILE.pem] [--packages 'PACKAGE_LIST'] [--guest Launchpad_ID] ..."
	echo
	echo "Parameters:"
	echo
	echo "  --rw                    - OPTIONAL; screenbin by default creates"
	echo "                            a session where the owner has read-write"
	echo "                            access, and all guests have read-only;"
	echo "                            if this parameter is given, the owner"
	echo "                            and all guests will have read-write"
	echo "                            access to the shared session"
	echo
	echo "  --instance Instance_ID  - OPTIONAL; if only once instance is"
	echo "                            active, screenbin will use that"
	echo "                            instance; if more than one is active,"
	echo "                            you will need to tell screenbin which"
	echo "                            instance_id to use"
	echo
	echo "  --ec2-keypair FILE.pem  - OPTIONAL; default ~/.ssh/ec2-keypair.pem"
	echo "                            this is the local user's ec2-keypair as"
	echo "                            required to ssh into the EC2 machine's"
	echo "                            ubuntu account"
	echo
	echo "  --packages PACKAGE_LIST - OPTIONAL; this is a list of packages to"
	echo "                            be installed on the EC2 machine"
	echo "                            note that this list should be white"
	echo "                            space separated, but quoted such that"
	echo "                            it is recognized as a single argument"
	echo
	echo "  --guest Launchpad_ID    - OPTIONAL; screenbin will retrieve"
	echo "                            this user's ssh key as stored in"
	echo "                            Launchpad and install that into"
	echo "                            a guest user's authorized_keys file"
	echo "                            on the target EC2 machine;"
	echo "                            you may add multiple --guest entries"
	echo "                            to share a screen with several people,"
	echo "                            or use a quoted, whitespace list of"
	echo "                            Launchpad IDs"
	echo
	exit 1
}

check_dep() {
	which "$1" >/dev/null || error "Missing dependency [$1]"
}

DEPS="ec2-describe-instances"
for i in $DEPS; do
	check_dep "$i"
done

# Extract parameters
INSTANCE_ID=
GUEST=
PACKAGES=
READWRITE=
while [ ! -z "$1" ]; do
	case "$1" in
		--rw)
			READWRITE=1
			shift
		;;
		--ec2-keypair)
			EC2_KEYPAIR="$2"
			shift 2
		;;
		--instance)
			INSTANCE_ID="$2"
			shift 2
		;;
		--guest)
			GUEST="$2 $GUEST"
			shift 2
		;;
		--packages)
			PACKAGES="$2"
			shift 2
		;;
		*)
			usage
		;;
        esac
done

if [ -z "$EC2_KEYPAIR" ]; then
	EC2_KEYPAIR="$HOME/.ssh/ec2-keypair.pem"
fi

if [ ! -r "$EC2_KEYPAIR" ]; then
	error "You should configure your ec2 ssh keypair"
fi

key=

my_ssh=
# This could be parameterized for non-standard keypairs
for i in id_rsa.pub id_dsa.pub; do
	if [ -r "$HOME/.ssh/$i" ]; then
		my_ssh=`cat "$HOME/.ssh/$i"`
		break
	fi
done
if [ -z "$my_ssh" ]; then
	error "Could not find your public ssh key"
fi

# Look for running instances
rc=0
instances=`ec2-describe-instances | grep "INSTANCE.*running"` || rc=$?
if [ "$rc" != "0" ]; then
	echo "No running instances"
	echo
	echo "Perhaps try starting an instance with:"
	echo "  ec2-run-instances <IMAGE_ID> -k ec2-keypair"
	echo "-----------------------------------"
	echo "Available images:"
	echo
	ec2-describe-images
	echo
	echo "Or see:"
	echo " * http://uec-images.ubuntu.com/releases/"
	echo "-----------------------------------"
	error "No running instances"
fi

count=`echo "$instances" | wc -l`
if [ $count -eq 1 ]; then
	hostname=`echo "$instances" | awk '{print $4}'`
	echo "Info: Found exactly 1 running instance [$hostname]"
elif [ $count -gt 1 ]; then
	if echo "$instances" | grep -qs "$INSTANCE_ID"; then
		hostname=`echo "$instances" | grep "$INSTANCE_ID" | awk '{print $4}'`
	else
		echo "Multiple instances found"
		echo
		echo "-----------------------------------"
		ec2-describe-instances | grep "^INSTANCE"
		echo "-----------------------------------"
		echo
		error "Multiple instances found; please specify with --instance INSTANCE_ID"
	fi
else
	error "No running instances"
fi

echo "Info: Connecting to your EC2 machine for initial setup..."
ssh -t -i $EC2_KEYPAIR "ubuntu@$hostname" "exit" || true

echo "Info: Preparing your EC2 machine...this may take a few minutes..."

packages="$PACKAGES"
guest="guest"
cryptpw="ubXWbZ4Ffn.mg"		# password = guest

ssh -i $EC2_KEYPAIR "ubuntu@$hostname" "set -e; \
	sudo /usr/bin/apt-get -q -y install $packages; \
	mkdir ~/.byobu; \
	byobu-launcher-install; \
"
if [ "$READWRITE" = "1" ]; then
	ssh -i $EC2_KEYPAIR "ubuntu@$hostname" "set -e; \
		ssh-import-lp-id $GUEST; \
		byobu -d -m -S class -t shell motd+shell; \
	"
	echo "Info: screen setup successfully!"
	echo
	echo "All users are peers and admins as user 'ubuntu', with read/write access."
	echo
	echo "Please tell [$GUEST] to:"
	echo "  ssh -C ubuntu@$hostname"
	echo "using ssh public key authentication"
	echo
else
	ssh -i $EC2_KEYPAIR "ubuntu@$hostname" "set -e; \
		sudo chmod 6755 /usr/bin/screen; \
		sudo chmod 755 /var/run/screen; \
		printf \"aclumask guest+r guest-w guest-x\naclchg guest +r-w-x '#?'\naclchg guest +x 'prev,next,select,detach'\nmultiuser on\n\" > ~/.screenrc; \
		sudo sed -i 's/PasswordAuthentication no//' /etc/ssh/sshd_config || true; \
		printf \"PasswordAuthentication yes\nAllowTcpForwarding no\nMatch User guest\n  ForceCommand exec screen -x ubuntu/class\n\" | sudo tee -a /etc/ssh/sshd_config; \
		sudo useradd -m -s /bin/bash -p $cryptpw $guest || true; \
		sudo chown -R root:root /home/guest; \
		sudo touch /home/guest/.screenrc; \
		sudo /etc/init.d/ssh restart; \
		byobu -c /usr/share/byobu/profiles/byoburc -d -m -S class -t shell motd+shell; \
	"
	echo "Info: screen setup successfully!"
	echo
	echo "Please tell your guests to:"
	echo "  ssh -C $guest@$hostname"
	echo "with password=guest"
	echo
	echo "As the host, you should connect with:"
	echo "  ssh -i $EC2_KEYPAIR ubuntu@$hostname"
	echo "to control the session"
	echo
fi
