#!/bin/sh -e

find "$1" | grep include > includes
sort includes|uniq -u > includes2
IDIR=$(cat includes2|tr '\n' ' '|sed -ne 's/\.\.\//-I\.\.\//gp')

PNME=$(grep PACKAGE_NAME Makefile|cut -f3 -d' ')
VNUM=$(grep '[0-9][0-9]*:[0-9][0-9]*:[0-9][0-9]*' Makefile|cut -f3 -d' ')

# the below might need adjusting if the linker args span multiple lines... guess we'll find out
LIBS=$(grep '.*_LIBS = ' Makefile|cut -f3 -d' ')

MNSO="$(printf '%s.so.%s.%s.%s' "${PNME}" "$(echo $VNUM|cut -f1 -d:)" "$(echo $VNUM|cut -f2 -d:)" "$(echo $VNUM|cut -f3 -d:)")"

for c in $(ls *.c|cut -f1 -d.)
do
    cc -DHAVE_CONFIG_H -I. -I.. -I../include $IDIR -c $c.c -o $c.o
done

cc *.o -shared -o "${MNSO}" $LIBS

for i in "$(printf "$PNME.so.%s" "$(echo $VNUM|cut -f1 -d:)")" "$(printf "$PNME.so.%s.%s.%s" "$(echo $VNUM|cut -f1 -d:)" "$(echo $VNUM|cut -f2 -d:)" "$(echo $VNUM|cut -f3 -d:)")"
do
    ln -s "${MNSO}" "${i}"
done

cc *.o -r -o "$PNME.a"

