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

PACKAGE=$2
TARGET_DEVICE=$3
TARGET_DEVICE_PORT=$4
TARGET_DEVICE_HOME=$5

echo
echo "Deploying package to device with serial number of ${SERIALNUMBER}."
echo "Using SSH identity from ${SSHIDENTITY}."
echo

USAGE="$0 [serialnumber] [package] [target_device] [target_device_port] [target_device_home]"

if [[ -z $PACKAGE || -z $TARGET_DEVICE || -z $TARGET_DEVICE_PORT || -z $TARGET_DEVICE_HOME ]]; then
 echo ${USAGE}
 exit
fi

# lets make the ssh port forwarding back on, as the developer might have rebooted the device
echo "do port forwarding"
set +e
${SCRIPTPATH}/device_portforward ${TARGET_DEVICE_PORT} 3768
set -e
echo "done"
# check if we have .pro files or cpp/h files, if we do lets exit, as this deployment method is for QML projects
H_FILES=`find . -name *.h`
CPP_FILES=`find . -name *.cpp`

if [[ -z ${H_FILES} && -z ${CPP_FILES} ]]; then
  echo "Detected: QML project"
else
  echo "Detected: Hybrid project"
  echo " -> This deployment method is meant for QML projects only."
  echo "    Use Tools > Ubuntu Touch > C++"
  exit 1
fi

# Case lowered due to bug #1213902
PLAIN_PACKAGE=`basename ${PACKAGE,,}`
SCRIPTPATH=`dirname $0`

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

# -- actions --
$SCP ${PACKAGE} ${TARGET_DEVICE}:${TARGET_DEVICE_HOME}
adb_shell gdebi --n ${TARGET_DEVICE_HOME}/${PLAIN_PACKAGE}

# Commented out due to bug #1213902
#$SCRIPTPATH/qtc_device_restart_appslense ${SERIALNUMBER}
