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

APPLICATION=$2

if [[ -z ${APPLICATION} ]]; then
  echo "Close all instances of running applications."
  adb_shell kill -s 9 \`pidof qmlscene\`
else
  echo "Close the ${APPLICATION}."
  set +e
  IS_MOUNTED=`adb_shell mount | grep proc`
  set -e
  if [[ -z ${IS_MOUNTED} ]]; then
    adb_shell mount -t proc proc /proc
  fi

  PID_OF_APP=`adb_shell COLUMNS=1000 ps -ef|grep qmlscene|grep ${APPLICATION}|awk '{print $2}'`
  if [[ -z $PID_OF_APP ]]; then
    echo "  *no running instances of application*"
    exit 1
  fi

  echo " * application pid(s) is ${PID_OF_APP}."

  adb_shell kill -s 9 ${PID_OF_APP}

  if [[ -z ${IS_MOUNTED} ]]; then
    adb_shell umount /proc
  fi
  echo "Application has been closed."
fi
