#!/bin/sh

set -e

umask 0022

BUILD_ALL=${BUILD_ALL:-"0"}
BUILD_CORE=${BUILD_CORE:-"0"}
BUILD_ENTERPRISE=${BUILD_ENTERPRISE:-"0"}
BUILD_MASTERFILES=${BUILD_MASTERFILES:-"0"}
BUILD_NOVA=${BUILD_NOVA:-"0"}
BUILD_MP=${BUILD_MP:-"0"}
SETUP_MP=${SETUP_MP:-"0"}
HUB_IP=${HUB_IP:-"192.168.100.90"}

# install the custom PHP repository
if grep -iq ubuntu /etc/os-release; then
    add-apt-repository -y ppa:ondrej/php
else
    if [ ! -f "/etc/apt/sources.list.d/sury-php.list" ]; then
        apt-get update
        apt-get install -y lsb-release ca-certificates apt-transport-https software-properties-common gnupg2
        echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" | sudo tee /etc/apt/sources.list.d/sury-php.list
        wget -qO - https://packages.sury.org/php/apt.gpg | sudo apt-key add -
    fi
fi

# install nodejs and npm
if [ ! -f "/etc/apt/sources.list.d/nodesource.list" ]; then
    curl -fsSL https://deb.nodesource.com/setup_16.x | bash -
    apt-get install -y nodejs
fi

# install the custom PostgreSQL repository
if [ ! -f "/etc/apt/sources.list.d/pgdg.list" ]; then
    apt-get update
    apt-get install -y lsb-release ca-certificates apt-transport-https software-properties-common gnupg2
    echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list
    wget -qO - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
fi

# install the build and runtime dependencies
apt-get update
apt-get install -y \
    acl \
    automake \
    build-essential \
    bison \
    flex \
    git \
    libacl1-dev \
    libapreq2-dev \
    libaprutil1-dev \
    libcurl4-openssl-dev \
    libldap2-dev \
    liblmdb-dev \
    libtool \
    libdb-dev \
    libpam0g-dev \
    libpcre3-dev \
    libpq-dev \
    libssl-dev \
    libxml2-dev \
    lsb-release \
    pkg-config \
    postgresql-13 \
    unzip \
    zlib1g-dev

# compile and install the packages, if required
if [ $BUILD_CORE -gt 0 ]; then
    cd /northern.tech/cfengine/core \
        && ./autogen.sh \
        && make \
        && make install
fi

if [ $BUILD_ENTERPRISE -gt 0 ]; then
    cd /northern.tech/cfengine/enterprise \
        && ./autogen.sh \
        && make \
        && make install
fi

if [ $BUILD_MASTERFILES -gt 0 ]; then
    cd /northern.tech/cfengine/masterfiles \
        && ./autogen.sh \
        && make \
        && make install
fi

if [ $BUILD_MP -gt 0 ]; then
    cd /northern.tech/cfengine/mission-portal \
        && make deps \
        && make \
        && make install
fi

if [ $BUILD_NOVA -gt 0 ]; then
    cd /northern.tech/cfengine/nova \
        && ./autogen.sh --with-enterprise-api=/var/cfengine/httpd/php/bin/php-config \
        && make \
        && make install
fi

if [ $SETUP_MP -gt 0 ]; then
    cd /northern.tech/cfengine/mission-portal && make setup
fi

exit 0
