#!/usr/bin/env bash

# Exit on error
set -e

# Query OS and machine
uname=`uname`
machine=`gcc -dumpmachine`

# Number of parallel jobs
if [[ $uname == *MINGW* ]]; then
  jobs=$NUMBER_OF_PROCESSORS
elif [[ $uname == Darwin ]]; then
  jobs=$(sysctl -n hw.activecpu)
else
  jobs=$(nproc)
fi

# Set x86-64 environment
if [[ $uname == Darwin ]]; then
  x86_64=true
elif [[ $uname == *MINGW* ]] && [[ $BUILD_X86_64 == True ]]; then
  x86_64=true
elif [[ $uname != *MINGW* ]]; then
  if [[ $machine == *amd64* ]] || [[ $machine == *x86_64* ]]; then
    x86_64=true
  fi
fi

# Set make tool
if [[ $uname != *FreeBSD* ]]; then
  export MAKE=make
else
  export MAKE=gmake
fi

# Set sudo tool
if [[ $uname == Haiku ]]; then
  export SUDO=
elif [[ $uname == *MINGW* ]]; then
  export SUDO=true
else
  export SUDO=sudo
fi

# Set download tool
if [[ $uname != Darwin ]]; then
  export DL="wget -O"
else
  export DL="curl -L -o"
fi

# Package locations
smooth_location=https://github.com/enzo1982/smooth/archive/master.zip
boca_location=https://github.com/enzo1982/boca/archive/master.zip
freac_location=https://github.com/enzo1982/freac/archive/master.zip

# Build smooth
$DL smooth-master.zip $smooth_location

rm -fr smooth-master
unzip smooth-master.zip

cd smooth-master
config=$1
if [[ $uname != *MINGW* ]] && [[ $uname != Darwin ]]; then
  config=$config,bundledlibbz2,bundledlibfribidi,bundledlibjpeg,bundledlibpng,bundledlibxml2,bundledzlib

  if [[ $uname == Haiku ]]; then
    config=$config,bundledlibiconv
  fi
fi
$MAKE config=$config -j$jobs
$SUDO $MAKE config=$config install -j$jobs
cd ..

# Build BoCA
$DL boca-master.zip $boca_location

rm -fr BoCA-master
unzip boca-master.zip

cp smooth-master/include/smooth.h BoCA-master/include

cp -R smooth-master/include/smooth BoCA-master/include
cp -R smooth-master/include/smooth-js BoCA-master/include

if [[ $uname == *MINGW* ]]; then
  if [[ $x86_64 != true ]]; then
    mkdir BoCA-master/lib
    cp smooth-master/lib/libsmooth* BoCA-master/lib
  else
    mkdir BoCA-master/lib64
    cp smooth-master/lib64/libsmooth* BoCA-master/lib64
  fi
fi

cd BoCA-master
config=$1
if [[ $uname != *MINGW* ]] && [[ $uname != Darwin ]]; then
  config=$config,bundledlibexpat,bundledliburiparser,bundledzlib
fi
$MAKE config=$config -j$jobs
$SUDO $MAKE config=$config install -j$jobs
if [[ $uname == Linux ]]; then
  cd components/output/alsa
  $MAKE config=$config -j$jobs
  $SUDO $MAKE config=$config install -j$jobs
  cd ../../..
fi
cd ..

# Build fre:ac
$DL freac-master.zip $freac_location

rm -fr freac-master
unzip freac-master.zip

mkdir freac-master/cdk

cp -R BoCA-master/include freac-master/cdk

if [[ $uname == *MINGW* ]]; then
  if [[ $x86_64 != true ]]; then
    cp -R BoCA-master/lib freac-master/cdk
  else
    cp -R BoCA-master/lib64 freac-master/cdk
  fi
fi

cd freac-master
config=$1
$MAKE config=$config -j$jobs
$SUDO $MAKE config=$config install -j$jobs
cd ..
