#!/bin/bash
# Assist in API cleanup by finding published ("global") functions/variables
# that are not used by other code.
#

usage() {
    echo "Usage:
    cd [a clean checkout of all yast repositories]
    find-unused-published yast2/library/network/src/modules/NetworkPopup.rb" >&2
}


# $1 YaST Module in Ruby, pathname
published() {
    # lines like
    #    publish :function => :Add, :type => "boolean ()"
    # or new ruby hash style
    #    publish function: :Add, type: "boolean ()"
    # transformed to
    #    Add
    RES=`sed -n -e '/publish/s/[^>]*> :\([^,]*\),.*/\1/;T;p' "$1"`
    # file uses new ruby format
    if [ -z $RES ]; then
      RES=`sed -n -e '/publish/s/[^:]*: :\([^,]*\),.*/\1/;T;p' "$1"`
    fi

    echo $RES | tr -s "[[:blank:]]" "\n"
}

# stdin: one identifier per line
# $1: namespace
find_unused() {
    while read SYM; do
        grep -E -r "$1(\.|::|->)$SYM" > /dev/null || echo $SYM
    done
}

if [ $# -ne 1 ]; then
    usage
    exit 1
fi

if [ ! -f $1 ]; then
    echo "ERROR: File '$1' do not exist" >&2
    usage
    exit 2
fi

NAMESPACE="${1##*/}"
NAMESPACE="${NAMESPACE%.rb}"
published "$1" | find_unused "$NAMESPACE"
