#!/bin/bash
# vim: set ts=4 sw=4 sts=4 et :

set -eu

## helpers ------------------------------------------------

# Whether we need sudo
if [ $(id -u) != 0 ]; then
    sudo=sudo
else
    sudo=
fi

# Use escape sequences only if both stdout/stderr are
# opened on a terminal.
if [ -t 1 ] && [ -t 2 ]; then
    _reset=$(tput sgr0)
    _bold=$(tput bold)
    _red=$(tput bold && tput setaf 1)
    _blue=$(tput bold && tput setaf 4)
else
    _reset=
    _bold=
    _red=
    _blue=
fi

bold() { echo -n "${_bold}$@${_reset}"; }
red()  { echo -n "${_red}$@${_reset}"; }
blue() { echo -n "${_blue}$@${_reset}"; }

confirm() {
    local message=${1:-Are you sure?}
    local header="Message from Kali developers"
    local line=

    echo "┏━($(blue $header))"
    while read -r line; do
        echo "┃ $line"
    done <<< $message
    echo -n "┗━[Y/n]: "

    read -r
    [ "$REPLY" ] && REPLY=${REPLY,,} || REPLY=y

    case "$REPLY" in
        y|yes) return 0 ;;
        *) return 1 ;;
    esac
}

vrun() {
    echo "$(bold '#' $@)"
    "$@"
}

## main ---------------------------------------------------

if [ $# -eq 0 ]; then
    echo "ERROR: missing arguments" >&2
    echo "Usage: $0 PACKAGE..." >&2
    exit 1
fi

message="We will install the following package(s):
$@

Do you want to proceed?"

if confirm "$message"; then
    vrun $sudo apt update
    vrun $sudo apt install -y "$@"
    echo -n "Done. "
else
    echo -n "Aborted. "
fi

echo -n "Press Enter to finish. "
read -r
