#!/bin/sh
#
# edb-as-13-setup	Initialization operations for EDB Postgres Advanced Server 13

# PGVERSION is the full package version, e.g., 13.0
# Note: the specfile inserts the correct value during package build
PGVERSION=13.21.27
# PGMAJORVERSION is major version, e.g., 13 (this should match PG_VERSION)
PGMAJORVERSION=`echo ${PGVERSION} | cut -d. -f1`
# PGENGINE is the directory containing the postmaster executable
# Note: the specfile inserts the correct value during package build
PGENGINE=/usr/edb/as13/bin

# The second parameter is the new database version, i.e. $PGMAJORVERSION in this case.
# Use  "edb-as-$PGMAJORVERSION" service, if not specified.
SERVICE_NAME="$2"
if [ x"$SERVICE_NAME" = x ]
then
    SERVICE_NAME=edb-as-$PGMAJORVERSION
fi

USAGE_STRING=$"
Usage: $0 {initdb} [SERVICE_NAME]

Script is aimed to help sysadmin with basic database cluster administration.

The SERVICE_NAME is used for selection of proper unit configuration file; For
more info and howto/when use this script please look at the doc file
$README_RPM_DIST.  The 'edb-as-13' string is used when no SERVICE_NAME is explicitly
passed.

Available operation mode:
  initdb        Create a new EDB Postgres Advanced Server database cluster. This is
		usually the first action you perform after EDB Postgres Advanced Server
		 server installation.

Environment:
  PGSETUP_INITDB_OPTIONS     Options carried by this variable are passed to
                             subsequent call of \`initdb\` binary (see man
                             initdb(1)).
  PGSETUP_DEBUG              Set to '1' if you want to see debugging output."

# note that these options are useful at least for help2man processing
case "$1" in
    --version)
	echo "edb-as-setup $PGVERSION"
        exit 0
        ;;
    --help|--usage)
        echo "$USAGE_STRING"
        exit 0
        ;;
esac

# this parsing technique fails for PGDATA pathnames containing spaces,
# but there's not much I can do about it given systemctl's output format...
PGDATA=`systemctl show -p Environment "${SERVICE_NAME}.service" |
                sed 's/^Environment=//' | tr ' ' '\n' |
                sed -n 's/^PGDATA=//p' | tail -n 1`
if [ x"$PGDATA" = x ]; then
    echo "failed to find PGDATA setting in ${SERVICE_NAME}.service"
    exit 1
fi

# Find the unit file for new version.
if [ -f "/etc/systemd/system/${SERVICE_NAME}.service" ]
then
    SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
elif [ -f "/usr/lib/systemd/system/${SERVICE_NAME}.service" ]
then
    SERVICE_FILE="/usr/lib/systemd/system/${SERVICE_NAME}.service"
else
    echo "Could not find systemd unit file ${SERVICE_NAME}.service"
    exit 1
fi

# Log file for initdb
PGLOG=/var/lib/edb/as$PGMAJORVERSION/initdb.log

# Get data directory from the service file
PGDATA=`sed -n 's/Environment=PGDATA=//p' "${SERVICE_FILE}"`

export PGDATA

# For SELinux we need to use 'runuser' not 'su'
if [ -x /sbin/runuser ]
then
    SU=runuser
else
    SU=su
fi

script_result=0

# initdb action
perform_initdb(){
    if [ ! -e "$PGDATA" ]; then
        mkdir -p "$PGDATA" || return 1
        chown enterprisedb:enterprisedb "$PGDATA"
        chmod go-rwx "$PGDATA"
    fi
    # Clean up SELinux tagging for PGDATA
    [ -x /sbin/restorecon ] && /sbin/restorecon "$PGDATA"

    # Create the initdb log file if needed
    if [ ! -e "$PGLOG" -a ! -h "$PGLOG" ]; then
        touch "$PGLOG" || return 1
        chown enterprisedb:enterprisedb "$PGLOG"
        chmod go-rwx "$PGLOG"
        [ -x /sbin/restorecon ] && /sbin/restorecon "$PGLOG"
    fi

    # Initialize the database
    initdbcmd="$PGENGINE/initdb --pgdata='$PGDATA' --auth='ident'"
    initdbcmd+=" $PGSETUP_INITDB_OPTIONS"

    $SU -l enterprisedb -c "$initdbcmd" >> "$PGLOG" 2>&1 < /dev/null

    # Create directory for postmaster log files
    mkdir "$PGDATA/log"
    chown enterprisedb:enterprisedb "$PGDATA/log"
    chmod go-rwx "$PGDATA/log"
    [ -x /sbin/restorecon ] && /sbin/restorecon "$PGDATA/log"

    if [ -f "$PGDATA/PG_VERSION" ]; then
        return 0
    fi
    return 1
}

initdb(){
    if [ -f "$PGDATA/PG_VERSION" ]; then
        echo $"Data directory is not empty!"
        echo
        script_result=1
    else
        echo -n $"Initializing database ... "
        if perform_initdb; then
            echo $"OK"
        else
            echo $"failed, see $PGLOG"
            script_result=1
        fi
        echo
    fi
}

# See how we were called.
case "$1" in
    initdb)
        initdb
        ;;
    *)
        echo >&2 "$USAGE_STRING"
        exit 2
esac

exit $script_result
