#!/bin/bash

source assets/shell/colors
source assets/config/deps/dependencies

### DEPENDENCY CHECK & INSTALLER

echo -e "\n  ${LCY}Dependency and Privilege Check running...${CRS}\n"

### PRIVILEGES

if (( $(id -u) == 0 )); then                                                        ### AM I ROOT?
    echo -e "    ${GRN}Privilege check passed...${CRS}\n"

else 
    echo -e "    ${RED}Privilege check failed... Please run script with sudo or as root!${CRS}\n"
    exit 1
fi

### DEPENDENCIES
     
dep_check() {
    local pkg="$1"

    if dpkg -s "$pkg" >/dev/null 2>&1; then
        echo "$pkg" >>/tmp/installed_dev
    else
        echo "$pkg" >>/tmp/missing_dev
    fi
}

for pkg in "${deps[@]}"; do
    dep_check "$pkg"
done  

installed="$(cat /tmp/installed_dev 2>/dev/null)"
missing="$(cat /tmp/missing_dev 2>/dev/null)"

if ! [  "$missing" ]; then
    echo -e "\n    ${GRN}Dependencies met. Proceeding...${CRS}\n"
else
    echo -e "\n    ${RED}Following dependencies are missing :${CRS}\n\n$missing"
    while true; do
        echo -e "\n  ${YEL}Do you wish to install via APT?"
        read -p "  (Y/n) --> " install_dep
        echo -e "${CRS}"
        if [[ "$install_dep" = "" || "$install_dep" = "y" || "$install_dep" = "Y" ]]; then
            sudo apt update && sudo apt install -y $missing --simulate
            echo -e "\n    ${GRN}Dependencies installed. Proceeding...${CRS}\n"
            sudo rm /tmp/installed_dev /tmp/missing_dev 2>/dev/null
            break
        elif [[ "$install_dep" == "n" || "$install_dep" = "N" ]]; then
            echo -e "\n    ${RED}Missing dependencies... Exiting!${CRS}\n"
            sudo rm /tmp/installed_dev /tmp/missing_dev 2>/dev/null
            exit 1
        else
            echo -e "\n ${YEL}Invalid response... Try again...\n\n  ${GRN}Y ${YEL}= (Yes, install dependencies and continue)\n  ${RED}N ${YEL}= (No, don't install dependencies and exit)${CRS}\n "
        fi
    done
fi