#! /bin/sh

OS=`uname -s`
DEBUG=0

create_linux_config_h() {
    cat <<EOF > src/config.h
#ifndef _CONFIG_H
#define _CONFIG_H
#include <endian.h>
#endif /* _CONFIG_H */
EOF
}

create_darwin_config_h() {
    cat <<EOF > src/config.h
#ifndef _CONFIG_H
#define _CONFIG_H
#include <architecture/byte_order.h>

#ifdef __LITTLE_ENDIAN__
#define __DO_SWAP_BYTES
#endif /* _DO_SWAP_BYTES */
#endif /* _CONFIG_H */
EOF
}

create_common_build_mk() {
    if [ "$DEBUG" = 1 ]; then
        cat <<'EOF' > mk/build.mk
CGFLAGS		= -g -fno-inline
EOF
	else
		cat <<'EOF' > mk/build.mk
CGFLAGS		=
EOF
    fi

	cat <<'EOF' >> mk/build.mk
CWFLAGS		= -Wall
COFLAGS		= -O2
CFLAGS		= $(CGFLAGS) $(CWFLAGS) $(COFLAGS)
EOF
}

create_linux_build_mk() {
    create_common_build_mk $@

    cat <<'EOF' >> mk/build.mk
LLFLAGS		= -shared -Wl,-soname=$(SONAME)

STATIC		= lib$(LIBNAME).a

SONAME_SHORT	= lib$(LIBNAME).so
SONAME		= $(SONAME_SHORT).$(VERSION_MAJOR)
SONAME_FULL	= $(SONAME_SHORT).$(VERSION)

PREFIX      = /usr/local
EOF
}

create_darwin_build_mk() {
    create_common_build_mk $@

    cat <<'EOF' >> mk/build.mk
LLFLAGS		= -dynamiclib -current_version $(VERSION)

STATIC      = lib$(LIBNAME).a

SONAME_SHORT	= lib$(LIBNAME).dylib
SONAME		= lib$(LIBNAME).$(VERSION_MAJOR).dylib
SONAME_FULL	= lib$(LIBNAME).$(VERSION).dylib

PREFIX      = /usr/local
EOF
}

for arg in $@; do
    case $arg in
        "--enable-debug")
            DEBUG=1
        ;;
    esac
done

if [ ! -d "mk" ]; then
    mkdir -m 0755 mk
fi

case $OS in
    Linux)
        create_linux_config_h
		create_linux_build_mk
    ;;

    Darwin)
        create_darwin_config_h
		create_darwin_build_mk
    ;;
esac