#!/bin/bash
#
# snuk-mozilla
# Snukware Mozilla Runtime Validator
#

VERSION="1.2"

PASS=0
FAIL=0


ok()
{
    printf "  [OK]   %s\n" "$1"
    ((PASS++))
}


fail()
{
    printf "  [FAIL] %s\n" "$1"
    ((FAIL++))
}


info()
{
    printf "  [INFO] %s\n" "$1"
}


check_dependency()
{
    local DIR="$1"
    local ELF="$2"
    local DEP="$3"


    #
    # Mozilla private libraries
    #
    if [[ -f "$DIR/$DEP" ]]; then
        return 0
    fi


    #
    # Basic runtime libraries
    #
    case "$DEP" in
        libc.so.*|\
        libm.so.*|\
        libpthread.so.*|\
        libdl.so.*|\
        librt.so.*|\
        libgcc_s.so.*|\
        libstdc++.so.*|\
        ld-linux*.so.*)
            return 0
            ;;
    esac


    #
    # System libraries
    #
    if ldconfig -p 2>/dev/null | grep -Fq "$DEP"; then
        return 0
    fi


    return 1
}



check_mozilla()
{
    local NAME="$1"
    local DIR="$2"
    local BIN="$3"

    local MISSING=0


    echo
    echo "=== $NAME ==="


    if [[ ! -d "$DIR" ]]; then
        info "not installed"
        return
    fi


    ok "directory $DIR"


    if [[ -f "$DIR/$BIN" ]]; then
        ok "binary $BIN"
    else
        fail "missing binary $BIN"
        return
    fi


    if [[ -f "$DIR/libxul.so" ]]; then
        ok "libxul.so"
    else
        fail "missing libxul.so"
        return
    fi



    while read -r elf
    do

        while read -r dep
        do

            [[ -z "$dep" ]] && continue


            if ! check_dependency "$DIR" "$elf" "$dep"
            then
                fail "$(basename "$elf") -> $dep"
                ((MISSING++))
            fi


        done < <(
            readelf -d "$elf" 2>/dev/null |
            awk '
            /NEEDED/ {
                gsub(/\[|\]/,"",$5);
                print $5
            }'
        )


    done < <(
        find "$DIR" \
            -type f \
            \( -name "*.so" -o -name "plugin-container" \)
    )


    if [[ "$MISSING" -eq 0 ]]; then
        ok "runtime dependencies verified"
    fi


    #
    # Real startup test
    #
    case "$BIN" in

        firefox|thunderbird|seamonkey)

            if "$DIR/$BIN" --version >/dev/null 2>&1
            then
                ok "startup test"
            else
                fail "startup test"
            fi
            ;;

    esac
}



echo
echo "Snuk Mozilla Runtime Validator v$VERSION"
echo



check_mozilla \
    "Firefox" \
    "/usr/lib64/firefox" \
    "firefox"



check_mozilla \
    "Thunderbird" \
    "/usr/lib64/thunderbird" \
    "thunderbird"



check_mozilla \
    "SeaMonkey" \
    "/usr/lib64/seamonkey" \
    "seamonkey"



echo
echo "=== SUMMARY ==="
echo

echo "Passed : $PASS"
echo "Failed : $FAIL"


if [[ "$FAIL" -eq 0 ]]
then
    echo
    echo "Mozilla runtime is healthy."
    exit 0
else
    echo
    echo "Mozilla runtime problems detected."
    exit 1
fi
