#!/bin/bash -ex

COMMON="meson curl git make file bzip2 $CC"

case "$DISTRO" in
  osx:*)
    brew update
    for pkg in jansson openssl zlib meson; do
        brew ls --versions $pkg || brew install $pkg
        brew outdated $pkg || brew upgrade $pkg || true
    done
    ;;

  debian:*|ubuntu:*)
    # This solves an intermittant error when fetching packages on debian
    sed -i 's|httpredir.debian.org|ftp.us.debian.org|g' /etc/apt/sources.list

    apt-get clean

    while ! apt-get update; do
        sleep 5
    done

    while ! apt-get -y \
        -o Dpkg::Options::="--force-confdef" \
        -o Dpkg::Options::="--force-confnew" \
        dist-upgrade; do
        sleep 5
    done

    while ! apt-get -y install $COMMON \
        build-essential pkg-config libssl-dev zlib1g-dev libjansson-dev; do
        sleep 5
    done
    ;;

  fedora:*)
    dnf -y clean all
    dnf -y --setopt=deltarpm=0 update
    dnf -y install $COMMON pkgconfig openssl-devel zlib-devel jansson-devel findutils
    ;;

  centos:*)
    yum -y clean all
    yum -y --setopt=deltarpm=0 update
    yum install -y yum-utils
    yum config-manager -y --set-enabled PowerTools
    yum -y install epel-release
    yum -y install $COMMON pkgconfig openssl-devel zlib-devel jansson-devel findutils gcc
    sed -i 's|>=1\.0\.2|>=1\.0\.1|' meson.build
    ;;
esac
