#!/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

FOLDERNAME=$2
DESKTOP_FILENAME=$3
MAIN_QML=$4
TARGET_DEVICE_HOME=$5
TARGET_DEVICE_DESKTOP_PATH=$6
TARGET_DEVICE=$7
TARGET_DEVICE_PORT=$8

USAGE="$0 [serialnumber] [foldername] [desktop_filename] [main_qml] [target_device_home] [target_device_desktop_path] [target_device] [target_device_port]"

if [[ -z ${DESKTOP_FILENAME} || -z ${FOLDERNAME} ]]; then
	echo ${USAGE}
	exit
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

if [[ -z ${TARGET_DEVICE_DESKTOP_PATH} ]]; then
	TARGET_DEVICE_DESKTOP_PATH=${TARGET_DEVICE_HOME}/.local/share/applications
fi

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}"

COMMAND="qmlscene ${TARGET_DEVICE_HOME}/${FOLDERNAME}/${MAIN_QML} --desktop_file_hint=${TARGET_DEVICE_DESKTOP_PATH}/${DESKTOP_FILENAME}"

# make a tar package
tar -cjf ${FOLDERNAME}.tar.bz2 ${FOLDERNAME}

# remove old files
$SSH rm -f ${TARGET_DEVICE_DESKTOP_PATH}/${DESKTOP_FILENAME}
$SSH rm -rf ${TARGET_DEVICE_HOME}

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

# transfer and extract the tar package to the device
$SCP ${FOLDERNAME}.tar.bz2 ${TARGET_DEVICE}:${TARGET_DEVICE_HOME}
$SSH "cd ${TARGET_DEVICE_HOME}; tar -xvf ${FOLDERNAME}.tar.bz2"

# install desktop file on the device
$SSH ln -s ${TARGET_DEVICE_HOME}/${FOLDERNAME}/${DESKTOP_FILENAME} ${TARGET_DEVICE_DESKTOP_PATH}

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

# run the application on the device
$SSH "bash -ic '${COMMAND}'"
