
#!/bin/bash
#
# snuk-audit-mozilla.sh
# Snukware Mozilla Runtime Audit Module
#

SNuk_MOZILLA_VERSION="1.3"

snuk_mozilla_check_one()
{
    local NAME="$1"
    local DIR="$2"
    local BIN="$3"
    local MISSING=0
    local ELF
    local DEP

    echo
    echo "=== Mozilla: $NAME ==="

    if [[ ! -d "$DIR" ]]; then
        echo "[INFO] $NAME not installed"
        return 0
    fi

    echo "[OK]   directory $DIR"

    if [[ ! -f "$DIR/$BIN" ]]; then
        echo "[FAIL] missing binary $DIR/$BIN"
        return 1
    fi

    echo "[OK]   binary $BIN"

    if [[ ! -f "$DIR/libxul.so" ]]; then
        echo "[FAIL] missing $DIR/libxul.so"
        return 1
    fi

    echo "[OK]   libxul.so"

    # Prüft tatsächliche Loader-Auflösung einschließlich RUNPATH/RPATH.
    while IFS= read -r ELF; do
        while IFS= read -r DEP; do
            [[ -z "$DEP" ]] && continue
            echo "[FAIL] $(basename "$ELF") :: $DEP"
            ((MISSING++))
        done < <(
       		LD_LIBRARY_PATH="$DIR${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" \
    		ldd "$ELF" 2>/dev/null | grep 'not found' 
		)
    done < <(
        find "$DIR" -type f \
            \( -name '*.so' -o -name 'plugin-container' \) \
            -print 2>/dev/null
    )

    if (( MISSING > 0 )); then
        echo "[FAIL] $NAME has $MISSING unresolved dependencies"
        return 1
    fi

    echo "[OK]   runtime dependencies"

    case "$BIN" in
        firefox|thunderbird|seamonkey)
            if "$DIR/$BIN" --version >/dev/null 2>&1; then
                echo "[OK]   startup test"
            else
                echo "[FAIL] startup test"
                return 1
            fi
            ;;
    esac

    return 0
}

snuk_mozilla_check()
{
    local FAILS=0

    snuk_mozilla_check_one "Firefox" \
        "/usr/lib64/firefox" "firefox" || ((FAILS++))

    snuk_mozilla_check_one "Thunderbird" \
        "/usr/lib64/thunderbird" "thunderbird" || ((FAILS++))

    snuk_mozilla_check_one "SeaMonkey" \
        "/usr/lib64/seamonkey" "seamonkey" || ((FAILS++))

    if (( FAILS > 0 )); then
        echo "[FAIL] Mozilla audit: $FAILS component(s) failed"
        return 1
    fi

    echo "[OK]   Mozilla audit"
    return 0
}

# Bei direktem Aufruf als eigenständiges Prüfprogramm arbeiten.
if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
    echo "Snukware Mozilla Runtime Audit v$SNuk_MOZILLA_VERSION"
    snuk_mozilla_check
    exit $?
fi
