#!/bin/sh
# This program is free software: you can redistribute it and/or modify it
# under the terms of the the GNU General Public License version 3, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR
# PURPOSE.  See the applicable version of 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/>.
#
# Copyright (C) 2014 Canonical, Ltd.
#
# Author: Sergio Schvezov <sergio.schvezov@canonical.com>

export LC_ALL=C

usage() {
cat <<EOF
usage: $0 [OPTIONS]

Creates and runs click apps

OPTIONS:
  -h	Show this message
  -s    Specify the serial of the device to install (see adb $ADBOPTS devices)

  --bzr-source 	bzr sources used to backreference the package
  --dir      	directory holding the package to build
  --provision   Install resulting click and run tests
  --no-clean    Don't clean temporary directories
  --extra-deps  Packages required in the chroot which are not part of the SDK
  --arch        Target architecture, requires a created click chroot
                (defaults to arch all)
  --framework   Target click framework, requires a created click chroot
                (defaults to ubuntu-sdk-13.10)
  --session	Run in a chroot session.
EOF
}

ADBOPTS=""
PROVISION=""
SOURCE=""
BZR_SOURCE=""
NO_CLEAN=""
EXTRA_DEPS=""
ARCH="all"
FRAMEWORK="ubuntu-sdk-13.10"
MAINTMODE=""
SESSION_NAME="click-buddy."`date +%Y%m%d`".$$"
SESSION_OPTS=""

TEST_DIR='tests/autopilot'
DEVICE_USER='phablet'

ARGS=$(getopt -o s:h -l "maint-mode,extra-deps:,bzr-source:,provision,no-clean,framework:,dir:,arch:,help,session" -n "$0" -- "$@")

if [ $? -ne 0 ] ; then
    exit 1
fi
eval set -- "$ARGS"

while true; do
    case "$1" in
        -h|--help)
            usage
            exit 0
            ;;
        -s)
            shift
            ADBOPTS="-s $1"
            shift
            ;;
        --provision)
            shift
            PROVISION=1
            ;;
        --bzr-source)
            shift
            BZR_SOURCE="$1"
            shift
            ;;
        --dir)
            shift
            SOURCE="$(readlink -f $1)"
            shift
            ;;
        --no-clean)
            shift
            NO_CLEAN=1
            ;;
		--arch)
			shift
			ARCH="$1"
			shift
			;;
		--framework)
			shift
			FRAMEWORK="$1"
			shift
			;;
		--extra-deps)
			shift
			EXTRA_DEPS="$1"
			shift
			;;
		--maint-mode)
			shift
			MAINTMODE=1
			;;
		--session)
			shift
			SESSION_OPTS="--session-name $SESSION_NAME"
			;;
        --)
            shift
            break
            ;;
    esac
done

builddir=$(mktemp -d)
installdir=$(mktemp -d)
if [ -z "$NO_CLEAN" ]; then
    trap 'rm -rf "$builddir" "$installdir"' EXIT
fi

if [ -z "$SOURCE" ]; then
	SOURCE="$(readlink -f $(pwd))"
fi

if [ ! -f $SOURCE/CMakeLists.txt ]; then
    echo "$SOURCE not a valid source dir"
    usage
    exit 1
fi

workdir=$(pwd)
cd $builddir

CMAKE_PARAMS="-DINSTALL_TESTS=off -DCLICK_MODE=on \
	-DBZR_REVNO=$(cd $SOURCE; bzr revno)"

if [ -n "$BZR_SOURCE" ]; then
	CMAKE_PARAMS="$CMAKE_PARAMS -DBZR_SOURCE=$BZR_SOURCE"
fi

set -e
if [ "$ARCH" = "all" ]; then
	cmake "$SOURCE" $CMAKE_PARAMS
	make DESTDIR=$installdir install
else
	if [ -n "$EXTRA_DEPS" ] && [ -z "$SESSION_OPTS" ]; then
		echo "Please either give a session name, or pass --maint-mode to install in main chroot"
		exit 1
	fi
	cd "$SOURCE"
	if [ -n "$EXTRA_DEPS" ] && [ -n "$SESSION_OPTS" ]; then
		trap 'click chroot -a$ARCH -f$FRAMEWORK end-session $SESSION_NAME' \
		   	EXIT HUP INT TERM
		click chroot -a$ARCH -f$FRAMEWORK begin-session "$SESSION_NAME"
		click chroot -a$ARCH -f$FRAMEWORK maint $SESSION_OPTS apt-get update
		click chroot -a$ARCH -f$FRAMEWORK maint $SESSION_OPTS apt-get install --yes $EXTRA_DEPS
	fi
	if [ -n "$MAINTMODE" ]; then
		trap 'click chroot -a$ARCH -f$FRAMEWORK maint apt-get autoremove --yes $EXTRA_DEPS' \
		   	EXIT HUP INT TERM
		click chroot -a$ARCH -f$FRAMEWORK maint apt-get update
		click chroot -a$ARCH -f$FRAMEWORK maint apt-get install --yes $EXTRA_DEPS
	fi
	click chroot -a$ARCH -f$FRAMEWORK run $SESSION_OPTS cmake $CMAKE_PARAMS
	click chroot -a$ARCH -f$FRAMEWORK run $SESSION_OPTS make
	click chroot -a$ARCH -f$FRAMEWORK run $SESSION_OPTS make DESTDIR=$installdir install
fi

if [ ! -f "$installdir/manifest.json" ]; then
	echo Building failed, check environment
	exit 1
fi

click build $installdir
if [ "$workdir" != "$(pwd)" ]; then
	cp *.click $workdir
fi

if [ -n "$PROVISION" ]; then
    set -e
    for click in *.click; do
        adb $ADBOPTS push "$click" /tmp
        adb $ADBOPTS shell sudo -u $DEVICE_USER bash -ic "pkcon install-local --allow-untrusted /tmp/$click"
    done

    adb $ADBOPTS shell mkdir -p /home/$DEVICE_USER/autopilot
    adb $ADBOPTS push $SOURCE/tests/autopilot /home/$DEVICE_USER/autopilot
    adb $ADBOPTS shell chown -R "$DEVICE_USER":"$DEVICE_USER" /home/$DEVICE_USER/autopilot
    set +e

    echo Allowing autopilot to play well with apparmor
    phablet-config autopilot --dbus-probe enable
    echo "Ready to run autopilot"
fi

if [ -n "$NO_CLEAN" ]; then
    echo build dir was $builddir
    echo install dir was $installdir
fi
