#!/bin/bash
set -euo pipefail

apt install -y sudo lsb-release wget

here=$(dirname "${BASH_SOURCE[0]}")
here=$(readlink -f "$here")
ubuntu="$(lsb_release -s -r)"

setup_directories() {
  cd "$here"
  mkdir -p build/linux
  cp -f build/Makefile.linux build/linux/Makefile
  cd build/linux
}

install_prerequisites() {
  # install Apache Arrow libs
  # NOTE: Pinned to Ubuntu Focal
  wget https://apache.bintray.com/arrow/ubuntu/apache-arrow-archive-keyring-latest-focal.deb
  sudo apt install -y -V ./apache-arrow-archive-keyring-latest-focal.deb
  sudo apt update -y
  sudo apt install -y -V libparquet-dev liblz4-dev libzstd-dev libthrift-dev \
    libsnappy-dev libthrift-dev libbrotli-dev libz-dev

  # Install prereqs based on https://github.com/apache/parquet-cpp#linux
  sudo apt install -y libboost-dev g++ libboost-filesystem-dev \
    libboost-program-options-dev libboost-regex-dev \
    libboost-system-dev libboost-test-dev \
    libssl-dev libtool bison flex pkg-config libreadline-dev libncurses-dev

  # Install prereqs based on https://github.com/apache/arrow/tree/master/cpp
  sudo apt install -y cmake \
    libboost-dev \
    libboost-filesystem-dev \
    libboost-system-dev
}

build_sqlite() {
  if [ ! -e ../../sqlite/sqlite3 ]; then
    ( cd "../.." && ./build-sqlite )
  fi
}

set_icu_version() {
  case "$ubuntu" in
    14.04)
      export ICU_VERSION=52-1
      ;;
    16.04)
      export ICU_VERSION=55-1
      ;;
    18.04)
      export ICU_VERSION=60-2
      ;;
    20.10)
      export ICU_VERSION=67-1
      ;;
    *)
    echo "unsure what libicu version to use" >&2
    exit 1
  esac

  export ICU_VERSION_U=${ICU_VERSION//-/_}
}

main() {
  set_icu_version
  setup_directories
  install_prerequisites
  build_sqlite

  if [ -v PREBUILT ]; then
    fetch_prebuilt_libs
  fi

  optimizations="-O3"
  if [ -v COVERAGE ]; then
    optimizations="-fprofile-arcs -ftest-coverage"
  fi

  make ${lib_locs[@]-} "$@" OPTIMIZATIONS="$optimizations"
}

main "$@"