#!/bin/sh -e

# Set the variable sys_arch so that we can change the
# build procedure depending on the host arch. Currently,
# we are only supporting i686 and x86_64.
sys_arch="$(uname -m)"

# Bootstrap if the package isn't installed yet.
cpt l -q musl || {
    ./configure \
        --prefix="$PWD/tmp"

    make ALL_TOOLS+=obj/musl-gcc
    make ALL_TOOLS+=obj/musl-gcc lib/musl-gcc.specs
    make ALL_TOOLS+=obj/musl-gcc install
    cp lib/musl-gcc.specs "$PWD/tmp/lib"
    export CC="$PWD/tmp/bin/musl-gcc"
}

./configure \
    --prefix=/usr \
    --syslibdir=/usr/lib

make
make DESTDIR="$1" install

mkdir -p "$1/usr/bin"

case "$sys_arch" in
    x86_64) ln -s /usr/lib/ld-musl-x86_64.so.1 "$1/usr/bin/ldd" ;;
    i*86)
        ln -s libc.so                  "$1/usr/lib/libc.musl-x86.so"
        ln -s ../lib/ld-musl-i386.so.1 "$1/usr/bin/ldd"
    ;;
esac

# Install BSD compatibility headers.
clinst -Dm755 -t "$1/usr/include/sys" cdefs.h queue.h tree.h

# Install getconf.
"${CC:=cc}" --static getconf.c -o "$1/usr/bin/getconf"

# Install getent
clinst -Dm755 -t "$1/usr/bin" getent