#!/bin/bash
# Copyright 2013 Canonical Ltd.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; version 2.1.
#
# 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Author: Juhapekka Piiroinen <juhapekka.piiroinen@canonical.com>

. `dirname $0`/functions.inc

APP_LAUNCHER=$2
FOLDERNAME=$3
DESKTOP_FILENAME=$4
MAIN_QML=$5
TARGET_DEVICE_HOME=$6
TARGET_DEVICE=$7
TARGET_DEVICE_PORT=$8
# potential prefix that should be prepended to the target app path
shift
APP_LAUNCH_PREFIX=$8
shift
EXTRA_COMMAND_LINE_ARGS=$8

APP_ID=$(echo ${DESKTOP_FILENAME}|sed "s/\.desktop//")

USAGE="$0 [serialnumber] [app_launcher] [foldername] [desktop_filename] [main_qml] [target_device_home] [target_device] [target_device_port] [optional_app_launch_prefix] [optional_extra_command_line_args]"


if [[ -z ${FOLDERNAME} ]]; then
	echo ${USAGE}
	exit
fi

if [[ ! -e "${FOLDERNAME}/${DESKTOP_FILENAME}" ]]; then
	echo "Reading desktop file from manifest"
	DESKTOP_FILENAME=$(grep desktop ${FOLDERNAME}/manifest.json | cut -d: -f2 | sed "s/\"//g" | tr -d ' ')
	echo "Trying ${PWD}/${FOLDERNAME}/${DESKTOP_FILENAME}"

	if [[ ! -e "${FOLDERNAME}/${DESKTOP_FILENAME}" ]]; then
		echo "No desktop file found";
		exit 1;
	fi
fi

if [[ -z ${APP_LAUNCHER} ]]; then
	APP_LAUNCHER=qmlscene
fi

if [[ -z ${MAIN_QML} ]]; then
	MAIN_QML=main.qml
fi

if [[ -z ${TARGET_DEVICE_PORT} ]]; then
	TARGET_DEVICE_PORT=2222
fi

if [[ -z ${TARGET_DEVICE} ]]; then
	TARGET_DEVICE=phablet@127.0.0.1
fi

if [[ -z ${TARGET_DEVICE_HOME} ]]; then
	TARGET_DEVICE_HOME=/home/phablet/dev_tmp
fi

SSH_CRED="ssh -i ${SSHIDENTITY} -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -p${TARGET_DEVICE_PORT}"
SCP="scp -i ${SSHIDENTITY} -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -P${TARGET_DEVICE_PORT}"
SSH="ssh -i ${SSHIDENTITY} -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -p${TARGET_DEVICE_PORT} ${TARGET_DEVICE}"
RSYNC="rsync --delete -avzP -e"

# get dbus session addrss from the device
DBUS_SESSION_BUS_ADDRESS=`$SSH "cat ~/.cache/upstart/dbus-session|grep DBUS_SESSION_BUS_ADDRESS"`

#read additional arguments from the desktop file
echo "Trying to read additional arguments from ${FOLDERNAME}/${DESKTOP_FILENAME}"
ARGS_FROM_DESKTOP=
IFS=', ' read -a ARGUMENTS <<< $(cat "${FOLDERNAME}/${DESKTOP_FILENAME}" | grep Exec | cut -d = -f 2)
LIMIT=${#ARGUMENTS[@]}
for ((a=1; a <= LIMIT ; a++))  # Double parentheses, and naked "LIMIT"
do
  #if we have a relative path, prefix it with the target home path
  if [[ ${ARGUMENTS[$a]} == "-I" ]]
  then
     IMPORT_PATH=${ARGUMENTS[$a+1]}
     if [[ "${IMPORT_PATH}" != /*  ]]
     then
        IMPORT_PATH=$(echo "${IMPORT_PATH}" | sed "s;\./;;" | sed "s;^;${TARGET_DEVICE_HOME}\/${APP_ID}\/;")
     else
        echo "Please use only relative paths for imports in the desktop file"
        exit 1
     fi
     ARGS_FROM_DESKTOP="-I ${IMPORT_PATH} ${ARGS_FROM_DESKTOP}"
  fi
done
echo "IMPORT: ${ARGS_FROM_DESKTOP}"

COMMAND="test -f /etc/ubuntu-touch-session.d/\$(getprop ro.product.device).conf && for myenv in \$(cat /etc/ubuntu-touch-session.d/\$(getprop ro.product.device).conf); do `echo \"export\" \\\$myenv`; done ; export ${DBUS_SESSION_BUS_ADDRESS=}; APP_ID=${APP_ID} ${APP_LAUNCHER} ${ARGS_FROM_DESKTOP} ${APP_LAUNCH_PREFIX}${TARGET_DEVICE_HOME}/${APP_ID}/${MAIN_QML} --desktop_file_hint=${TARGET_DEVICE_HOME}/${APP_ID}/${DESKTOP_FILENAME} ${EXTRA_COMMAND_LINE_ARGS}"
echo "Going to execute: ${COMMAND}"

# make sure that the device has the target directory
$SSH mkdir -p ${TARGET_DEVICE_HOME}
$SSH mkdir -p ${TARGET_DEVICE_HOME}/${APP_ID}

# transfer the package to the device
$RSYNC "${SSH_CRED}" ${FOLDERNAME}/ ${TARGET_DEVICE}:${TARGET_DEVICE_HOME}/${APP_ID}

echo "Starting the application .... "

# fix the desktopfile Exec path
$SSH sed -i "s/^Exec=.*//g" ${TARGET_DEVICE_HOME}/${APP_ID}/${DESKTOP_FILENAME}
$SSH "echo 'Exec=/usr/bin/${COMMAND}' >> ${TARGET_DEVICE_HOME}/${APP_ID}/${DESKTOP_FILENAME}"

# run the application on the device
$SSH "bash -ic 'source /etc/profile; ${COMMAND}'"
