# This is supposed to be run on a Ubuntu host or container
cat /etc/*release | grep Ubuntu || exit 1

git_pull_rebase_helper()
{
  git reset --hard HEAD
  git pull
}

if [ -z "$NO_DOWNLOAD" ] ; then
  sudo apt-add-repository -y ppa:vala-team/ppa
  sudo apt-get update -qq
  sudo apt-get install -qq libfuse-dev libglib2.0-dev cmake libc6-dev binutils valac libgee-0.8-dev gcc-multilib g++-multilib libc6-dev-i386
fi

# Determine which architecture should be built
if [[ "$(arch)" = "i686" || "$(arch)" = "x86_64" ]] ; then
  ARCH=($arch)
  else
    echo "Architecture could not be determined"
    exit 1
fi

if [ ! -d AppImageKit ] ; then
  git clone https://github.com/probonopd/AppImageKit.git
fi
cd AppImageKit/
git_pull_rebase_helper

APP=AppImageAssistant

cd ./LibcWrapGenerator
valac --pkg gee-0.8 --pkg posix --pkg glib-2.0 --pkg gio-2.0 ./LibcWrapGenerator.vala
sudo ./LibcWrapGenerator --target 2.14 --libdir /lib --output libcwrap.h
sudo cp ./libcwrap.h /usr/include/
cd -
export CC='gcc -U_FORTIFY_SOURCE -include /usr/include/libcwrap.h'
cmake . && make clean && make $APP

VERSION=$(git rev-list --count HEAD).$(git describe --tags | cut -d - -f 3)

mkdir -p ../out || true
if [[ "$ARCH" = "x86_64" ]] ; then AI=$APP"-"$VERSION"-x86_64.AppImage"; fi
if [[ "$ARCH" = "i686" ]] ; then AI=$APP"-"$VERSION"-i386.AppImage"; fi
rm -f ../out/$AI || true
mv $APP ../out/$AI
