#!/bin/bash

set -o xtrace

# update_repos() - Function that updates linux repositories
function update_repos {
    if [ -f /var/onap/files/sources.list ]; then
        cp /var/onap/files/sources.list /etc/apt/sources.list
    fi
    if [ -f /var/onap/files/proxyrc ]; then
        source /var/onap/files/proxyrc
        cp /var/onap/files/proxyrc /etc/profile.d/proxy.sh

        if [ -f /etc/apt/apt.conf ]; then
            echo "Acquire::http::Proxy \"${http_proxy}\";" >>  /etc/apt/apt.conf
            echo "Acquire::https::Proxy \"${https_proxy}\";" >>  /etc/apt/apt.conf
        fi
        if [ -d /etc/apt/apt.conf.d ] & [ ! -f /etc/apt/apt.conf.d/70proxy.conf ]; then
            echo "Acquire::http::Proxy \"${http_proxy}\";" >>  /etc/apt/apt.conf.d/70proxy.conf
            echo "Acquire::https::Proxy \"${https_proxy}\";" >>  /etc/apt/apt.conf.d/70proxy.conf
        fi
    fi
    apt-get update -qq -y
}

# is_package_installed() - Function to tell if a package is installed
function is_package_installed {
    if [[ -z "$@" ]]; then
        return 1
    fi
    dpkg -s "$@" > /dev/null 2> /dev/null
}

# install_packages() - Install a list of packages
function install_packages {
    local package=$@
    update_repos
    apt-get install -y -qq $package
}

# install_package() - Install specific package if doesn't exist
function install_package {
    local package=$1
    if ! is_package_installed $package; then
        update_repos
        apt-get install -y -qq $package
    fi
}

# uninstall_packages() - Uninstall a list of packages
function uninstall_packages {
    local packages=$@
    apt-get purge -y -qq $packages
}

# uninstall_package() - Uninstall specific package if exists
function uninstall_package {
    local package=$1
    if is_package_installed $package; then
        apt-get purge -y -qq $package
    fi
}