#!/usr/bin/env bash

. depends
. common

library_exists ()
{
    ld -melf_i386 -l$1 -o /dev/null >/dev/null 2>&1
    return $?
}

header_exists ()
{
    echo "#include <$1>" | g++ -x c++ - -fsyntax-only -o /dev/null >/dev/null 2>&1
    return $?
}

STATUS_MISSING=$(mktemp)

gauge_deps_libraries ()
{
    local I=0
    for lib in "${DEPENDS_LIBRARIES[@]}"
    do
        # unholy
        local percent=$(echo "scale=2; $I / ${#DEPENDS_LIBRARIES[*]} * 100" | bc | sed s/\\.[0-9]\\+//)
        printf 'XXX\n%d\nChecking for library "%s"...\nXXX\n' $percent "$lib"
        if ! library_exists $lib; then
            echo $lib >$STATUS_MISSING
            return 1
        fi
        I=$(($I + 1))
    done 
    return 0
}

gauge_deps_headers ()
{
    local I=0
    for header in "${DEPENDS_HEADERS[@]}"
    do
        # unholy
        local percent=$(echo "scale=2; $I / ${#DEPENDS_HEADERS[*]} * 100" | bc | sed s/\\.[0-9]\\+//)
        printf 'XXX\n%d\nChecking for header <%s>...\nXXX\n' $percent "$header"
        if ! header_exists $header; then
            echo $header >$STATUS_MISSING
            return 1
        fi
        I=$(($I + 1))
    done 
    return 0
}

BAD=0

check_all_deps ()
{
    gauge_deps_libraries | whiptail --title "Checking libraries" --gauge "Please wait" 6 78 0
    if ! [ ${PIPESTATUS[0]} == 0 ]; then
        $DIALOG --title "Error: missing library" --msgbox "It appears that you don't have library '$(cat $STATUS_MISSING)' installed. Please install it and try again." 8 78
        BAD=1
    fi
    gauge_deps_headers | whiptail --title "Checking headers" --gauge "Please wait" 6 78 0
    if ! [ ${PIPESTATUS[0]} == 0 ]; then
        $DIALOG --title "Error: missing header" --msgbox "It appears that you don't have header '$(cat $STATUS_MISSING)' installed. Please install it and try again." 8 78
        BAD=1
    fi
    if [ $BAD == 1 ]; then
        $DIALOG --title "Failure" --msgbox "It looks like you need to install some additional libraries, you can do that from main menu." 8 78
    else
        $DIALOG --title "Success" --msgbox "You have all the libraries you need to build and use cathook!" 7 68
    fi
}

check_all_deps
rm $STATUS_MISSING