#!/usr/bin/env bash
set -x
set -e

is_prod=false
args="$(getopt -o '' --long prod -- "$@")"
eval "set -- $args"
while true; do
    case "$1" in
        --prod) is_prod=true; shift;;
        --) shift; break;;
    esac
done

is_centos=false
is_rhel=false
is_rhel_registered=false
if [ -e /etc/centos-release ]; then
    is_centos=true
    yum install -y epel-release

    if [ "$is_prod" = true ]; then
        # IUS is needed for installing python36u-mod_wsgi on prod env
        yum localinstall -y https://centos7.iuscommunity.org/ius-release.rpm
    fi

elif grep -q "Red Hat" /etc/redhat-release; then
    is_rhel=true
    yum localinstall -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
    if subscription-manager status; then
        # See https://access.redhat.com/discussions/2217891#comment-1032701
        is_rhel_registered=true
        # libmemcached-devel can be installed directly if the machine is registered
        subscription-manager repos --enable "rhel-*-optional-rpms" --enable "rhel-*-extras-rpms"
    fi
fi

yum update -y

# "Development Tools" is the equivalent of build-essential
yum groupinstall -y "Development Tools"

RHVER="$(rpm -qf --queryformat="%{VERSION}" /etc/redhat-release)"
RHARCH="$(rpm -qf --queryformat="%{ARCH}" /etc/redhat-release)"
PGVER=10
if [ "$is_centos" = true ]; then
    # PostgreSQL $PGVER
    yum localinstall -y "https://yum.postgresql.org/$PGVER/redhat/rhel-$RHVER-$RHARCH/pgdg-centos$PGVER-$PGVER-2.noarch.rpm"

    # PGroonga
    # https://pgroonga.github.io/install/centos.html
    yum localinstall -y https://packages.groonga.org/centos/groonga-release-latest.noarch.rpm
elif [ "$is_rhel" = true ]; then
    if [ "$is_rhel_registered" = false ]; then
        echo "This machine is unregistered; installing libmemcached-devel from a CentOS mirror ..."
        yum localinstall -y http://mirror.centos.org/centos/7/os/x86_64/Packages/libmemcached-devel-1.0.16-5.el7.x86_64.rpm
    fi
    yum localinstall -y https://download.postgresql.org/pub/repos/yum/10/redhat/rhel-latest-x86_64/pgdg-redhat10-10-2.noarch.rpm
    yum localinstall -y https://packages.groonga.org/centos/groonga-release-latest.noarch.rpm
else
    # TODO only fedora29 for now
    dnf install -y "https://download.postgresql.org/pub/repos/yum/$PGVER/fedora/fedora-29-x86_64/pgdg-fedora$PGVER-$PGVER-4.noarch.rpm"
fi
