#!/usr/bin/env bash

# Check for missing or extra plugins in FreeBSD/pkg-plist
PLIST="FreeBSD/pkg-plist"

# Missing plugins
# If there's e.g. plugins/main/rotors
# Then lib/lebiniou/plugins/main/rotors/rotors.so should be in $PLIST

echo "Looking for missing plugins"
MISSING=0
for dir in input main output; do
    echo "  in $dir:"
    for p in `find plugins/$dir/ -type d -not -path '*/\.*' | sort`; do
        if [ $p != "plugins/$dir/" ]; then
            p=${p#"plugins/$dir/"}
            if [ $dir == "main" ] && [ $p != "include" -a $p != "test_beat_detection" ] || [ $dir != "main" ]; then
                q="lib/lebiniou/plugins/$dir/$p/$p.so"
                grep -q $q $PLIST
                if [ $? -eq 1 ]; then
                    echo " => $p: Missing"
                    MISSING=$((MISSING+1))
                fi
            fi
        fi
    done
    echo
done

echo "$MISSING missing plugins in $PLIST"

if [ $MISSING -gt 0 ]; then
    exit 1
else
    echo
fi


# Extraneous plugins
# If there's e.g. lib/lebiniou/plugins/main/rotors/rotors.so in $PLIST
# Then plugins/main/rotors/rotors.c should exist

echo "Looking for extraneous plugins"
EXTRANEOUS=0
for dir in input main output; do
    echo "  in $dir:"
    for p in `grep lib/lebiniou/plugins/$dir/ $PLIST | sort`; do
        p=${p%".so"}
        p=`echo $p | rev | cut -d"/" -f -1 | rev`
        q=plugins/$dir/$p/$p.c
        test -f $q
        if [ $? -eq 1 ]; then
            echo " => $p: Extraneous"
            EXTRANEOUS=$((EXTRANEOUS+1))
        fi
    done
    echo
done

echo "$EXTRANEOUS extraneous plugins in $PLIST"

if [ $EXTRANEOUS -eq 0 ]; then
    exit 0
else
    exit 1
fi
