#!/bin/sh
# build: makefile replacement because POSIX make sucks

die() {
    fmt=$1
    shift
    printf "$fmt\n" "$@" >&2
    exit 1
}

# FIXME: place these in a config.sh that is sourced to mirror current config.mk
version=0.0

prefix=/usr/local
manprefix=$prefix/share/man

cc=c99
ld=$cc
ar=ar
ranlib=ranlib

# FIXME: unquoted expansions to create word splitting are full or problems
#        saddly POSIX sh does not support arrays, it is not a sane shell
CFLAGS="-Wall -pedantic"
CPPFLAGS="-D_DEFAULT_SOURCE -D_BSD_SOURCE -D_GNU_SOURCE"
LDFLAGS=-s

# outdated target dependencies [...]
# return true if any dependencies are newer than target or target does not exist
outdated() {
    targ=$1
    shift
    ! [ -f "$targ" ] || [ "$(find "$@" -newer "$targ")" ]
}

# NOTE: bodies of for loops can be place in { }& to run in parallel...
# compile each source file to an object file
compile() {
    for c; do
        outdated "${c%.c}.o" "$c" || continue
        printf "compile %s\n" "$c"
        "$cc" $CFLAGS $CPPFLAGS -c -o "${c%.c}.o" "$c" || die "compile %s failed" "$c"
    done
}

# link each object file to create a binary
link() {
    for o; do
        outdated "${o%.o}" "$o" lib*.a || continue
        printf "link %s\n" "$o"
        "$ld" $LDFLAGS -o "${o%.o}" "$o" lib*.a || die "link %s failed" "$o"
    done
}

# create a library for each directory given
lib() {
    for d; do
        d=${d%/}
        lib=$d.a
        compile "$d"/*.c
        outdated "$lib" "$d"/*.o || continue
        printf "library %s\n" "$lib"
        "$ar" -r -c "$lib" "$d"/*.o || die "ar %s failed" "$lib"
        "$ranlib" "$lib" || die "ranlib %s failed" "$lib"
    done
}

clean() {
    rm -f *.o lib*/*.o lib*.a *.tar.gz sbase-box

    for f in *.c; do
        rm -f "${f%.c}"
    done
}

if [ $# -eq 0 ]; then
    set all
fi

while [ $# -gt 0 ]; do
    case $1 in
        install) ;;
        uninstall) ;;
        dist) ;;
        sbase-box) ;;
        clean)
            clean
            ;;
        all)
            lib lib*/
            compile *.c
            link *.o
            ;;
        *)
            lib lib*/
            compile "$1.c"
            link "$1.o"
            ;;
    esac
    shift
done
