1#!/bin/bash
2
3LOG=$(mktemp)
4
5# Exit handler
6function _exit () {
7    if [ $1 -ne 0 -a $1 -ne 333 ]; then
8        echo "$0: ERROR - last command exited with code $1, output:" >&2 && cat $LOG >&2
9    fi
10    rm -f $LOG
11    exit $1
12}
13
14trap '_exit $?' EXIT
15
16# Apt package installations (only ask Apt to install missing packages)
17function install_packages {
18    to_install=()
19    for pkg in "$@"; do
20        installed=$(/usr/bin/dpkg-query --show --showformat='${db:Status-Status}\n' $pkg 2>&1 | grep -ci installed)
21        [ $installed -eq 0 ] && to_install=("${to_install[@]}" $pkg)
22    done
23    if [ "${#to_install[@]}" -gt 0 ]; then
24        echo "Installing packages: ${to_install[@]}"
25        set -e
26        # quiet mode -q=2 implies -y
27        DEBIAN_FRONTEND=noninteractive apt-get -q=2 install "${to_install[@]}" >$LOG 2>&1
28        set +e
29    else
30        echo "All needed OS packages already installed ($@)"
31    fi
32}
33