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

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

USAGE="$0 [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

# 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


PLAIN_PACKAGE=`basename ${PACKAGE}`
SCRIPTPATH=`dirname $0`

SCP="scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -P${TARGET_DEVICE_PORT}"
SSH="ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -p${TARGET_DEVICE_PORT} ${TARGET_DEVICE}"
ADB="adb shell chroot /data/ubuntu /usr/bin/env -i PATH=/bin:/usr/bin:/sbin:/usr/sbin:/tools/bin"

# -- actions --
$SCP ${PACKAGE} ${TARGET_DEVICE}:${TARGET_DEVICE_HOME}
$ADB gdebi --n ${TARGET_DEVICE_HOME}/${PLAIN_PACKAGE}
$SCRIPTPATH/qtc_device_restart_appslense
