#!/bin/sh -e

CFLAGS="$CFLAGS -static -fPIC -fno-lto -fno-use-linker-plugin"
LDFLAGS="$LDFLAGS -static -fPIC -fno-lto -fno-use-linker-plugin"

sed -i 's/CFLAGS=.*//' Makefile
sed -i 's/$(CFLAGS)/$(BIGFILES) $(LDFLAGS) $(CFLAGS)/g' Makefile
sed -i 's^$(PREFIX)^/$(DESTDIR)/$(PREFIX)^g' Makefile
sed -i 's/gcc/cc/g' Makefile
sed -i s'^$(CC)^$(CC) $(LDFLAGS) $(CFLAGS)^g' Makefile-libbz2_so
sed -i 's/CFLAGS=.*//' Makefile-libbz2_so
sed -i 's/gcc/cc/g' Makefile-libbz2_so
sed -i 's/cq libbz2.a/-r/g' Makefile

make
mv a.out libbz2.a
# this is a temporary fix until we figure out what causes the shared object build to break
CFLAGS='-O2 -w -pipe -fPIC'
LDFLAGS='-fno-use-linker-plugin -fPIC'
make -f Makefile-libbz2_so

ln -sf bzip2 bunzip2
ln -sf bzip2 bzcat
for lib in libbz2.so libbz2.so.1 libbz2.so.1.0
do
    ln -sf libbz2.so.1.0.8 $lib
done

make DESTDIR="$1" PREFIX=/usr install
install -Dm755 libbz2.so.1.0.8 "$1/usr/lib/libbz2.so.1.0.8"
install -Dm644 bzip2.1         "$1/usr/share/man/man1/bzip2.1"
install -Dm644 bzlib.h         "$1/usr/include/bzlib.h"

for lib in libbz2.so libbz2.so.1 libbz2.so.1.0
do 
    ln -sf libbz2.so.1.0.8 "$1/usr/lib/$lib"
done
