#!/usr/bin/env bash

. common
. depends

$DIALOG --title "Install?" --backtitle "Installing" --yesno "The script will probably need to install some additional packages using apt, and this probably can break something, so you should use it at your own risk." 9 78
if [ $? == 1 ]; then exit; fi

package_exists ()
{
    dpkg -s $1 2>&1 | grep Status >/dev/null 2>&1
    return $?
}

gauge_deps_packages ()
{
    local I=0
    for package in "${DEPENDS_PACKAGES[@]}"
    do
        # unholy
        local percent=$(echo "scale=2; $I / ${#DEPENDS_PACKAGES[*]} * 100" | bc | sed s/\\.[0-9]\\+//)
        printf 'XXX\n%d\nChecking for package "%s"...\nXXX\n' $percent "$package"
        if ! package_exists $package; then
            printf 'XXX\n%d\nInstalling "%s"...\nXXX\n' $percent "$package"
            gksu -- apt install -y $package >/dev/null 2>&1
        fi
        I=$(($I + 1))
        # Sleep so the user sees the package name
        sleep 0.3
    done 
    return 0
}

if ! package_exists "gksu"; then
    $DIALOG --title "gksu not installed" --msgbox "You should install gksu first. Do that with\nsudo apt install gksu" 9 78
    exit
fi

gauge_deps_packages | whiptail --title "Installing packages" --gauge "Please wait" 6 78 0

$DIALOG --title "Success" --msgbox "Installed successfully." 8 78

if ! [ ${PIPESTATUS[0]} == 0 ]; then
    $DIALOG --title "Error: error" --msgbox "It appears that you have error. Please fix it." 8 78
fi