#!/bin/sh
# This file is part of Checkbox.
#
# Copyright 2013 Canonical Ltd.
# Written by:
#   Zygmunt Krynicki <zygmunt.krynicki@canonical.com>
#
# Checkbox is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3,
# as published by the Free Software Foundation.

#
# Checkbox 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Checkbox.  If not, see <http://www.gnu.org/licenses/>.


# Helper script to install all of the Debian dependencies
# =======================================================

set -e

# Ensure that CHECKBOX_TOP is not empty
if [ "$CHECKBOX_TOP" = "" ]; then
    echo "E: this script requires \$CHECKBOX_TOP"
    exit 100
fi

# Construct a list of required Debian packages.
debian_pkg_list="$(find "$CHECKBOX_TOP" -path '*/requirements/deb-*.txt' -exec cat "{}" \;  | grep -v '^#' | sort | uniq)"

# Check each one and install if required
echo "I: checking if the following Debian packages are installed:" $debian_pkg_list
dpkgs_to_install_list=""
for debian_pkg in $debian_pkg_list; do
    if [ "$(dpkg-query -s $debian_pkg 2>/dev/null | grep '^Status:')" != "Status: install ok installed" ]; then
        echo "I: package $debian_pkg is missing, queueing for install"
        dpkgs_to_install_list="$dpkgs_to_install_list $debian_pkg"
    fi
done
if [ -n "$dpkgs_to_install_list" ]; then
    if [ $(id -u) != 0 ]; then
        sudo apt-get install --quiet --quiet --yes $dpkgs_to_install_list
    else
        apt-get install --quiet --quiet --yes $dpkgs_to_install_list
    fi
fi
