#!/bin/sh
set -e

DIR="$1"
shift
DIR="${*:+${DIR:-.}/}"

mkdir -p "protos"

for f in ${*:--}
  do
    h="${f%.c}.h"
    (cd "$DIR";
    # functions
    egrep -h '^[a-zA-Z_]+.*[a-zA-Z_][a-zA-Z0-9_]*\(.*\)$' "$f"|
    grep -v '^static'|
    egrep -v '^void [a-z_]+_command\('|
    egrep -v '^struct session \*[a-z_]+_command\('|
    sed 's/.*/extern &;/'

    # variables
    egrep -h '^[a-zA-Z_][][a-zA-Z0-9_*, ]*[=;]' "$f"|
    grep -v '^static'|
    grep -v '^extern'|
    grep -v '^typedef'|
    sed 's/ *[=;].*//'|
    sed 's/.*/extern &;/'

    # function pointers
    egrep -h '^[a-zA-Z_]+ \(\*[a-zA-Z_]+\)\([][a-zA-Z0-9_*,. ]*\) *[=;]' "$f"|
    grep -v '^static'|
    grep -v '^extern'|
    grep -v '^typedef'|
    sed 's/ *[=;].*//'|
    sed 's/.*/extern &;/'
    ) >"protos/$h"
  done
