#!/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 --guest Launchpad_ID [--ec2-keypair FILE.pem] [--packages 'PACKAGE_LIST'] [--guest Launchpad_ID] ..."
	echo
	echo "Parameters:"
	echo
	echo "  --guest Launchpad_ID    - REQUIRED; 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
	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
	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=
while [ ! -z "$1" ]; do
	case "$1" in
		--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

if [ -z "$GUEST" ]; then
	usage
	error "You must specify a guest Launchpad id, --guest LP_ID"
fi

key=
friend_lp_ssh=
for i in $GUEST; do
	if ! key=`wget -O- https://launchpad.net/~$i/+sshkeys 2>/dev/null | sed -e 's/[^a-zA-Z0-9@: .\/=+-]//g'`; then
		error "Could not retrieve ssh key for [$i]"
else
		echo "Info: Retrieved ssh key for [$i]"
	fi
	friend_lp_ssh="$friend_lp_ssh$key\n"
done

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
	echo "  Perhaps try starting an instance with:"
	echo "    $ ec2-run-instances ami-814aaee8 -k ec2-keypair              # 32-bit"
	echo "  or"
	echo "    $ ec2-run-instances ami-a84aaec1 -k ec2-keypair -t c1.xlarge # 64-bit"
	echo
	echo "-----------------------------------"
	ec2-describe-instances
	echo "-----------------------------------"
	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
		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 screen vim"
guest="guest"
ssh -i $EC2_KEYPAIR "ubuntu@$hostname" "set -e; \
	sudo dpkg --configure -a; \
	sudo /usr/bin/apt-get -q -y install $packages; \
	sudo useradd -m -s /bin/bash $guest || true; \
	sudo mkdir -p -m 700 ~$guest/.ssh; \
	sudo chown ubuntu:ubuntu ~$guest/.ssh; \
	sudo touch ~$guest/.ssh/authorized_keys; \
	sudo chown ubuntu:ubuntu ~$guest/.ssh/authorized_keys; \
	sudo chmod 640 ~$guest/.ssh/authorized_keys; \
	sudo printf \"$friend_lp_ssh\" >> ~$guest/.ssh/authorized_keys; \
	echo '$my_ssh' | sudo tee -a ~$guest/.ssh/authorized_keys; \
	sudo chmod 640 ~$guest/.ssh/authorized_keys; \
	sudo chown root:$guest ~$guest/.ssh/authorized_keys; \
	sudo chown $guest:$guest ~$guest/.ssh; \
	sudo -u $guest '/usr/bin/select-screen-profile -s ubuntu-dark'; \
	sudo -u $guest '/usr/share/screen-profiles/screen-launcher-install'; \
	sudo touch ~$guest/.screenrc-windows; \
	echo 'syntax on' | sudo tee -a ~$guest/.vimrc; "

echo "Info: screen setup successfully!"
echo
echo "Please tell [ $GUEST] to:"
echo "  ssh -C $guest@$hostname"
echo
read -p "Hit <enter> to connect..." foo

ssh -C $guest@"$hostname"
