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

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

USAGE="$0 [foldername] [target_device] [target_device_port] [target_device_home]"

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

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

tar -cjf ${FOLDERNAME}.tar.bz2 ${FOLDERNAME}
$SSH mkdir -p ${TARGET_DEVICE_HOME}
$SCP ${FOLDERNAME}.tar.bz2 ${TARGET_DEVICE}:${TARGET_DEVICE_HOME}
$SSH "cd ${TARGET_DEVICE_HOME}; tar -xvf ${FOLDERNAME}.tar.bz2"
$SSH "cd ${TARGET_DEVICE_HOME}/${FOLDERNAME}; dh_make -p ${FOLDERNAME}_0.1 -s -y --createorig"
$SSH "cd ${TARGET_DEVICE_HOME}/${FOLDERNAME}; debuild -i -I -S -sa -us -uc -nc"
$SSH "cd ${TARGET_DEVICE_HOME}/${FOLDERNAME}; dpkg-buildpackage -us -uc -nc"
$SCP ${TARGET_DEVICE}:${TARGET_DEVICE_HOME}/${FOLDERNAME}*_* .
