#!/bin/sh -e
#
#    screen-profile-export
#    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/>.

PKG="byobu"
SHARE="/usr/share/$PKG"
DIR=`mktemp -t -d $PKG.XXXXXXXX` || error "Could not create a temporary directory"
# Grab list of available colors
colors=`find $SHARE/profiles/ -type f | sed "s/^.*\///" | sed "s/^.*-//" | sort -u | egrep -v "common|plain|NONE"`

# Make sure we clean up $DIR if we exit for any reason
trap "rm -rf "$DIR" 2>/dev/null || true" EXIT HUP INT QUIT TERM

usage() {
	echo
	echo "Usage:"
	echo " $0 [-c COLOR] -f TARGET.tar.gz"
	echo
	echo "If TARGET.tar.gz is unspecified, a randomly generated"
	echo "filename will be used."
	echo
	echo "COLOR is obtained interactively if unspecified; or one of:"
	for c in $colors; do
		echo " * $c"
	done
	echo
	exit 1
}

error() {
	echo "ERROR: $1" 1>&2
	[ "$generated" = "1" -a -f "$file" ] && rm -f "$file"
	exit 1
}

choose() {
	i=0
	x=
	selected=
	for x in $@; do
		i=$(expr $i + 1)
		[ $i -lt 10 ] && i=" $i"
		echo " $i. $x" 1>&2
	done
	echo
	count=1
	while /bin/true; do
		if [ $count -gt 5 ]; then
			error "Invalid selection"
		fi
		count=`expr $count + 1`
		if ! test $selected -gt 0 2>/dev/null; then
			echo -n "`gettext 'Choose'` [1 -$i]: "
			selected=`head -n1`
		elif ! test $selected -le $i 2>/dev/null; then
			echo -n "`gettext 'Choose'` [1 -$i]: "
			selected=`head -n1`
		else
			break
		fi
	done
	i=0
	for x in $@; do
		i=$(expr $i + 1)
		if [ "$i" = "$selected" ]; then
			SELECTED="$x"
			return 0
		fi
	done
	exit 1
}

hr() {
	echo "###############################################################################"
}

header() {
	hr
	echo "# This GNU Screen profile was generated by the $PKG-export"
	echo "# program, which is part of the $PKG package, and contains a"
	echo "# subset of the functionality available from the full package."
	echo "#"
	echo "# For more information, source code, questions, and bugs, see:"
	echo "#  * https://launchpad.net/$PKG"
	echo "#"
	echo "#    Copyright (C) 2008 Canonical Ltd."
	echo "#"
	echo "#    Author: Dustin Kirkland <kirkland@canonical.com>"
	echo "#"
	echo "#    This program is free software: you can redistribute it and/or modify"
	echo "#    it under the terms of the GNU General Public License as published by"
	echo "#    the Free Software Foundation, version 3 of the License."
	echo "#"
	echo "#    This program is distributed in the hope that it will be useful,"
	echo "#    but WITHOUT ANY WARRANTY; without even the implied warranty of"
	echo "#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the"
	echo "#    GNU General Public License for more details."
	echo "#"
	echo "#    You should have received a copy of the GNU General Public License"
	echo "#    along with this program.  If not, see <http://www.gnu.org/licenses/>."
	hr
}

sources() {
	# insert the common profile, replace the status exe path
	echo
	cat $SHARE/profiles/common | sed "s:$PKG-:\$HOME/.$PKG/$PKG-:"
	hr
	echo
	cat $SHARE/keybindings/f-keys
	hr
	echo
	hr
	cat "$SOURCE"
	hr
}


# Handle command line parameters
color=
file=
while [ $# -gt 1 ]; do
	case "$1" in
		-c)
			color="$2"
			shift 2
		;;
		-f)
			file="$2"
			shift 2
		;;
		*)
			usage
		;;
	esac
done

[ $# -eq 1 ] && file="$1"

if [ -z "$file" ]; then
	# Generate a temp archive filename
	while true; do
		file=`mktemp -t $PKG.XXXXXX` || error "Could not generate random filename"
		if [ ! -e "$file.tar.gz" ]; then
			mv -i "$file" "$file.tar.gz"
			file="$file.tar.gz"
			generated=1
			break
		else
			rm -f "$file"
		fi
	done
else
	echo "$file" | grep -qs "\.tar\.gz$" || error "Target file must be a '.tar.gz' archive"
	if [ -e "$file" ]; then
		echo `gettext "File exists"` " [$file]"
		echo -n "`gettext 'Remove file? [y/N] '`"
		remove=`head -n1`
		if [ "$remove" = "Y" -o "$remove" = "y" ]; then
			rm -f "$file"
		else
			exit 1
		fi
	fi
fi

# Obtain selections
count=1
while /bin/true; do
	if [ $count -gt 5 ]; then
		error "Invalid selection"
	fi
	SOURCE="$SHARE"/profiles/"$color"
	if [ -f "$SOURCE" ]; then
		break
	else
		# Try in the misc directory too
		SOURCE="$SHARE"/profiles/misc/"$color"
		if [ -f "$SOURCE" ]; then
			break
		fi
	fi
	echo
	echo `gettext "Select a color: "`
	choose $colors
	color=$SELECTED
	count=`expr $count + 1`
done

# Create workspace
PROFILE="$DIR/.screenrc"
STATUS="$DIR/.$PKG/status"
mkdir -p "$DIR/.$PKG/bin"
touch "$DIR/.$PKG/profile"
dpkg-query --show --showformat '${Package} ${Version}\n' $PKG > "$DIR/.$PKG/version" 2>/dev/null || true
echo "http://launchpad.net/$PKG" >> "$DIR/.$PKG/version"

# Copy status scripts
cp -a /usr/lib/$PKG/* "$DIR/.$PKG/bin"
cp -a /usr/bin/$PKG-status "$DIR/.$PKG"
cp -a /usr/bin/$PKG-janitor "$DIR/.$PKG"

# Generate the monolithic profile
header > "$PROFILE"
sources >> "$PROFILE"
cat /etc/$PKG/statusrc > "$STATUS"

# Some gardening
# Drop additional "source" calls
sed -i "s:^source .*::" "$PROFILE"
# Use .screenrc instead
sed -i "s:.$PKG/profile\":\.screenrc\":" "$PROFILE"
# Drop the F9->Menu key
sed -i "s:^bindkey -k k9 screen -t help:#bindkey -k k9 screen -t help:" "$PROFILE"

# tar up the results
tar --owner=root --group=root -zcf "$file" -C "$DIR" . || error "Could not create archive"

echo
echo "Success!"
echo
echo "  "`gettext "Profile"` ": [$color]"
echo "  "`gettext "Archive"` ": [$file]"
echo
echo `gettext "Extract the archive in your home directory on the target system."`
echo
