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

PROJECT=$1

if [[ ! -d "$PROJECT" ]]; then
  echo "Project not found ($PROJECT)."
  exit 123
fi

cd $PROJECT
if [[ -d debian ]]; then
  echo "Packaging already exists for project. Skipping.."
  exit
fi

PACKAGENAME=`basename $PWD|tr '[A-Z]' '[a-z]'`

# create packaging
dh_make -n -p ${PACKAGENAME}_0.1 -s --createorig --yes
if [[ ! -d debian ]]; then
  echo "Debian folder was not created!"
  exit 2
fi

pushd debian
# remove unfilled files
rm *.ex *.EX README* docs
popd

# add installable files
INSTALL_PATH=/usr/share/${PACKAGENAME}
DESKTOPFILE=/usr/share/applications
find . -mindepth 1 -maxdepth 3 -printf "%p ${INSTALL_PATH}\n"|grep -v ".user\|debian\|.desktop" | sed "s/^\.\///g" > debian/install
find *.desktop -printf "%p ${DESKTOPFILE}\n" >> debian/install

# check if we have .pro files or cpp/h files, if not then change architecture to any
H_FILES=`find . -name *.h`
CPP_FILES=`find . -name *.cpp`

if [[ -z ${H_FILES} && -z ${CPP_FILES} ]]; then
  echo "Detected: QML project"
  sed -i "s/^Architecture: any$/Architecture: all/g" debian/control
else
  echo "Detected: Hybrid project"
fi

# update package dependencies
SCRIPTPATH=`dirname $0`
QMLDEPS=`${SCRIPTPATH}/qtc_project_detect_qmldeps`
sed -i "s/^Depends:.*/${QMLDEPS}qmlscene/g" debian/control

