#!/bin/sh

# Should be included by a script. The includer should set the variable 
# $NATIVE to "true" if it wants native code compilation.

OCAMLBUILD=${OCAMLBUILD:="ocamlbuild -use-ocamlfind -classic-display"}
B="_build"
NL="
"

LIBS=""; ILIBS=""
BINS=""; IBINS=""
TOPS=""; ITOPS=""
SHRS=""; ISHRS=""
DOCS=""; IDOCS=""
MISC=""; IMISC=""
STBS=""; ISTBS=""
MANS=""; IMANS=""

add_lib ()      { LIBS="$LIBS $1"; ILIBS="$ILIBS$NL  \"$B/$1\" {\"$2\"}"; }
add_bin ()      { BINS="$BINS $1"; IBINS="$IBINS$NL  \"$B/$1\" {\"$2\"}"; }
add_toplevel () { TOPS="$TOPS $1"; ITOPS="$ITOPS$NL  \"$B/$1\" {\"$2\"}"; }
add_share ()    { SHRS="$SHRS $1"; ISHRS="$ISHRS$NL  \"$B/$1\" {\"$2\"}"; }
add_doc ()      { DOCS="$DOCS $1"; IDOCS="$IDOCS$NL  \"$B/$1\" {\"$2\"}"; }
add_misc ()     { MISC="$MISC $1"; IMISC="$IMISC$NL  \"$B/$1\" {\"$2\"}"; }
add_stublibs () { STBS="$STBS $1"; ISTBS="$ISTBS$NL  \"$B/$1\" {\"$2\"}"; }
add_man ()      { MANS="$MANS $1"; IMANS="$IMANS$NL  \"$B/$1\" {\"$2\"}"; }
add ()
{
    SRC=$2
    DST=$3
    if [ "$DST" = "" ]; then 
        DST=`basename $SRC`
    fi
    case $1 in
        lib)
            if [ "$NATIVE" = "true" ]; then 
                add_lib $SRC $DST
            else
                case $2 in
                    *.a | *.cmx | *.cmxa | *.cmxs) ;;
                    *) add_lib $SRC $DST ;;
                esac
            fi
            ;;
        bin)
            if [ "$NATIVE" = "true" ]; then 
                add_bin $SRC.native $DST
            else
                add_bin $SRC.byte $DST
            fi
            ;;
        share)    add_share $SRC $DST ;;
        toplevel) add_top $SRC.top $DST ;; 
        doc)      add_doc $SRC $DST ;;
        misc)     add_misc $SRC $DST ;;
        stublibs) add_stublibs $SRC $DST ;;
        man)      add_man $SRC $DST ;;
    esac
}

build () { $OCAMLBUILD $LIBS $BINS $DOCS $TOPS $SHRS $MISC $STBS $MANS; }
install ()
{
    cat > $1.install <<EOF 
opam-version: "1"
lib: [$ILIBS
]
bin: [$IBINS
]
toplevel: [$ITOPS
]
share: [$ISHRS
]
doc: [$IDOCS
]
misc: [$IMISC
]
stublibs: [$ISTBS
]
man: [$IMANS
]
EOF
}
