#!/usr/bin/env bash
##makedesc: Install postgresql (latest) and php-pgsql (if php is installed)

set -eo pipefail

installed() { command -v "$1" >/dev/null 2>&1; }

require() {
    local missing=()
    for pkg in "$@"; do
        installed "$pkg" || missing+=("$pkg")
    done
    if [ ${#missing[@]} -gt 0 ]; then
        if [ "$(uname -s)" = "Darwin" ]; then
            if installed brew; then
                brew install "${missing[@]}"
            else
                echo "ERROR: Missing: ${missing[*]}. Install manually or use brew." >&2
                exit 1
            fi
        else
            sudo apt install -y "${missing[@]}"
        fi
    fi
}

install() {
    if [ "$(uname -s)" = "Darwin" ]; then
        if installed brew; then
            brew install postgresql
            brew services start postgresql
        else
            echo "ERROR: Install Homebrew first." >&2
            exit 1
        fi
        return
    fi

    echo
    echo "==============================================="
    echo "Installing postgresql"
    echo "==============================================="
    echo

    require postgresql postgresql-contrib
    sudo service postgresql restart

    if installed php; then
        sudo apt install -y --autoremove php-pgsql phpmyadmin
    fi

    echo
    echo "Finish!"
    postgres --version
    echo
}

case "$1" in
    *) install ;;
esac
