#!/bin/bash

# Generate a list of plugins to exclude from the package by looking into
# them and checking:
# - if they are known non-free plugins
# - if they depend on a known non-free plugin

# First tell if there are known non-free plugins

SCRIPTDIR="../scripts"

if [ ! -d "$SCRIPTDIR" ] ; then
    echo "The script directory $SCRIPTDIR does not exist" >&2
    echo "Do not know where to check for plugins" >&2
    exit 1
fi

find_plugs () {

if [ -f non-free-plugins ] ; then

    # Check if any of the known non-free-plugins exist
    #echo "NON-FREE" # DEBUG
    for plugin in `cat non-free-plugins | grep -v ^\#`; do
     if [ -e "$SCRIPTDIR/$plugin" ] ; then
         if egrep -iq '(c).*Tenable Network Security' "$SCRIPTDIR/$plugin"; then
             echo "$plugin"
         fi
     fi
    done

    # Now check if there are any plugins that include any of the known non-free-plugins
    #echo "NON-FREE INCLUDEF" # DEBUG
    for includef in `cat non-free-plugins | grep '\.inc' | grep -v ^\#`; do
        # Only check if the include file is not there...
        # since it might have been restored from free sources
        if [ ! -e "$SCRIPTDIR/$includef" ] ; then
            total=`egrep -rl 'include\(.$includef.\)' $SCRIPTDIR |grep -v $includef | wc -l` 
            if [ -n "$total" ] && [ "$total" -ne 0 ] ; then
                grep -rl $includef $SCRIPTDIR |grep -v $includef 
            fi
        fi
    done

fi

if [ -f "depend-plugins" ] ; then

    # If there is a list of known plugins which depend on non-free plugins and they
    # are present, print them.
    #echo "DEPEND-PLUGIN" # DEBUG
    for plugin in `cat depend-plugins | grep -v ^#`; do
     if [ -e "$SCRIPTDIR/$plugin" ] ; then
         echo $plugin
    fi
    done

else

    # If there is no such list then find all the plugins that include a file which is
    # not present in the scripts directory by checking all of their includes
    # Notice that the include call can have spaces and the .inc filename can be delimited by
    # double quotes (") or simple quotes (')
    #echo "NO-DEPEND-PLUGIN" # DEBUG
    for plugin in $SCRIPTDIR/*; do
        for includef in `cat $plugin |perl -ne 'print $1."\n" if /include\s*\(.(.*).\)/'`; do
            if [ ! -e "$SCRIPTDIR/$includef" ] ; then
                echo $plugin
            fi
        done
    done


fi

}


# Sort and make unique the list of plugins found, output only the basename, not the full path
find_plugs |
sort -u |
while read file; do
    name=`basename $file`
    echo $name
done
    


exit 0
