#!/usr/bin/env bash

# omarchy:summary=Install PostgreSQL
# omarchy:requires-sudo=true

# Based: PostgreSQL built from source through asdf, with the headers the
# configure wants on Debian and brew's icu4c, OpenSSL and readline on the Mac,
# where icu4c is keg-only and has to be named to pkg-config and the linker.
# The build runs outside the caller's make, which would otherwise hand it
# MAKEFLAGS meant for something else.

set -eo pipefail

asdf_data=${ASDF_DATA_DIR:-$HOME/.asdf}
omarchy-pkg-add asdf
export PATH="$asdf_data/shims:$PATH"

echo -e "Installing PostgreSQL...\n"
omarchy-pkg-add autoconf linux=only bison flex libedit-dev linux=only libkrb5-dev linux=only \
  libldap2-dev linux=only libpam0g-dev linux=only libperl-dev linux=only postgresql-server-dev-all linux=only \
  libreadline-dev linux=only libssl-dev linux=only libxml2-dev linux=only libxslt1-dev linux=only \
  libyaml-dev linux=only pkg-config linux=only uuid-dev linux=only zlib1g-dev linux=only \
  icu4c darwin=only openssl@3 darwin=only readline darwin=only
if [[ $(omarchy-os) == darwin ]]; then
  icu=$(brew --prefix icu4c)
  export PKG_CONFIG_PATH="$icu/lib/pkgconfig${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}"
  export LDFLAGS="-L$icu/lib${LDFLAGS:+ $LDFLAGS}"
  export CPPFLAGS="-I$icu/include${CPPFLAGS:+ $CPPFLAGS}"
fi
cd /tmp && MAKEFLAGS='' MAKELEVEL=0 omarchy-dev-env-tool postgres
