##
##  postgresxl.spec -- OpenPKG RPM Package Specification
##  Copyright (c) 2000-2025 OpenPKG Project <http://openpkg.org/>
##
##  Permission to use, copy, modify, and distribute this software for
##  any purpose with or without fee is hereby granted, provided that
##  the above copyright notice and this permission notice appear in all
##  copies.
##
##  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
##  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
##  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
##  IN NO EVENT SHALL THE AUTHORS AND COPYRIGHT HOLDERS AND THEIR
##  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
##  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
##  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
##  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
##  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
##  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
##  OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
##  SUCH DAMAGE.
##

#   package versions
%define       V_postgresxl      9.5r1.4
%define       V_postgresxl_dist 9.5r1.4
%define       V_postgresxl_dir  9.5r1.4

#   package information
Name:         postgresxl
Summary:      Postgres XL (eXtensible Lattice) Database
URL:          http://www.postgres-xl.org/
Vendor:       Postgres XL Project
Packager:     OpenPKG Project
Distribution: OpenPKG Community
Class:        EVAL
Group:        Database
License:      BSD
Version:      %{V_postgresxl}
Release:      20161129

#   package options
%option       with_server       yes
%option       with_threads      no
%option       with_kerberos     no
%option       with_ldap         no

#   list of sources
Source0:      http://files.postgres-xl.org/postgres-xl-%{V_postgresxl_dist}.tar.gz
Source1:      rc.postgresxl
Source2:      pg_migrate
Source3:      pg_passwd
Patch0:       postgresxl.patch

#   build information
BuildPreReq:  OpenPKG, openpkg >= 20160101, make, gcc, flex, bison, gzip
PreReq:       OpenPKG, openpkg >= 20160101
BuildPreReq:  readline, zlib, openssl
PreReq:       readline, zlib, openssl
%if "%{with_kerberos}" == "yes"
BuildPreReq:  KERBEROS
PreReq:       KERBEROS
%endif
%if "%{with_ldap}" == "yes"
BuildPreReq:  openldap
PreReq:       openldap
%endif
Provides:     postgresql = %{version}

%description
    Postgres-XL (eXtensible Lattice) is an all-purpose fully ACID
    horizontally scalable SQL database system, based on PostgreSQL. It
    provides cluster-wide consistency and multi-tenant security.

%track
    prog postgresxl = {
        version   = %{V_postgresxl_dist}
        url       = http://www.postgres-xl.org/download/
        regex     = postgres-xl-(\d+\.\d+(?:\.\d+)?(?:r\d+\.\d+)?)\.tar\.gz
    }

%prep
    %setup -q -n postgres-xl-%{V_postgresxl_dist}
    %patch -p0

%build
    #   adjust source tree
    %{l_shtool} subst \
        -e 's;\(#define.*DEFAULT_PGSOCKET_DIR[^"]*"\)/tmp\("\);\1%{l_prefix}/var/postgresql/run\2;' \
        src/include/pg_config_manual.h
    %{l_shtool} subst \
        -e 's;^\(sqlmansect *=\).*$;\1 7;' \
        src/makefiles/Makefile.solaris
    %{l_shtool} subst \
        -e 's;# Shared library stuff;enable_shared = yes;g' \
        src/pl/plpgsql/src/Makefile

    #   configure package
    echo "ac_cv_func_isinf=no" >config.cache
    export CC="%{l_cc}"
    export CFLAGS="%{l_cflags -O} -pthread"
    export CPPFLAGS="%{l_cppflags readline}"
    export LDFLAGS="%{l_ldflags}"
    export LIBS=""
%if "%{with_kerberos}" == "yes"
    CPPFLAGS="$CPPFLAGS `krb5-config --cflags`"
    LIBS="$LIBS `krb5-config --libs`"
%endif
%if "%{with_ldap}" == "yes"
    LIBS="$LIBS -lldap -llber -lssl -lcrypto"
%endif
    export TAR="%{l_tar}"
    export YACC="bison -y"
    ./configure \
        --cache-file=./config.cache \
        --prefix=%{l_prefix} \
        --mandir=%{l_prefix}/man \
        --sysconfdir=%{l_prefix}/etc/postgresql \
        --includedir=%{l_prefix}/include/postgresql \
        --with-openssl \
        --with-readline \
        --with-zlib \
%if "%{with_threads}" == "yes"
        --enable-thread-safety \
%else
        --disable-thread-safety \
%endif
%if "%{with_kerberos}" == "yes"
        --with-krb5 \
        --with-krb-srvnam=postgresql \
%endif
%if "%{with_ldap}" == "yes"
        --with-ldap \
%endif
        --disable-shared

    #   build package
    %{l_make} %{l_mflags}

    #   rebuild pg_config with hard-coded path to avoid that it provides
    #   dynamically resolved paths which circumvent symlinks, etc.
    ( cd src/bin/pg_config
      %{l_shtool} subst \
          -e 's:find_my_exec(argv.0., mypath):0; strcpy(mypath, "%{l_prefix}/bin/pg_config"):' \
          pg_config.c
      %{l_make} %{l_mflags}
    ) || exit $?

    #   build PGXC addons
    ( cd contrib/pgxc_ctl     && %{l_make} %{l_mflags} ) || exit $?
    ( cd contrib/pgxc_clean   && %{l_make} %{l_mflags} ) || exit $?
    ( cd contrib/pgxc_monitor && %{l_make} %{l_mflags} ) || exit $?

%install
    #   perform standard installation procedure
    cp /dev/null register.txt
    %{l_make} %{l_mflags} install install-docs DESTDIR=$RPM_BUILD_ROOT

    #   install PGXC addons
    %{l_shtool} install -c -s -m 755 \
        contrib/pgxc_ctl/pgxc_ctl $RPM_BUILD_ROOT%{l_prefix}/bin/
    %{l_shtool} install -c -s -m 755 \
        contrib/pgxc_clean/pgxc_clean $RPM_BUILD_ROOT%{l_prefix}/bin/
    %{l_shtool} install -c -s -m 755 \
        contrib/pgxc_monitor/pgxc_monitor $RPM_BUILD_ROOT%{l_prefix}/bin/

    #   strip down installation
    rm -rf $RPM_BUILD_ROOT%{l_prefix}/share/doc
    strip $RPM_BUILD_ROOT%{l_prefix}/bin/* >/dev/null 2>&1 || true
    rm -f $RPM_BUILD_ROOT%{l_prefix}/man/man1/pgaccess.1
    rm -f $RPM_BUILD_ROOT%{l_prefix}/man/man1/pgtclsh.1
    rm -f $RPM_BUILD_ROOT%{l_prefix}/man/man1/pgtksh.1

    #   namespace adjustments to installation
    for prog in \
        createdb createlang createuser dropdb droplang clusterdb \
        dropuser initdb vacuumdb reindexdb; do
        mv  $RPM_BUILD_ROOT%{l_prefix}/bin/$prog \
            $RPM_BUILD_ROOT%{l_prefix}/bin/pg_$prog
        mv  $RPM_BUILD_ROOT%{l_prefix}/man/man1/$prog.1 \
            $RPM_BUILD_ROOT%{l_prefix}/man/man1/pg_$prog.1
    done
    ( cd $RPM_BUILD_ROOT%{l_prefix}/man/man7
      for man in *.7; do
          mv $man pg_$man
      done
    ) || exit $?

    #   create additional directories
    %{l_shtool} mkdir -f -p -m 755 \
        $RPM_BUILD_ROOT%{l_prefix}/var/postgresql/db \
        $RPM_BUILD_ROOT%{l_prefix}/var/postgresql/run

    #   install addon utilities
    %{l_shtool} install -c -m 755 %{l_value -s -a} \
        %{SOURCE pg_migrate} $RPM_BUILD_ROOT%{l_prefix}/bin/
    %{l_shtool} install -c -m 755 %{l_value -s -a} \
        -e "s;@l_bash@;%{l_bash};g" \
        %{SOURCE pg_passwd} $RPM_BUILD_ROOT%{l_prefix}/bin/

    #   adjust default configuration for hourly auto-vacuum operation
    %{l_shtool} subst \
        -e 's;^# *\(stats_start_collector *=\) *[^#]*\(#.*\);\1 on \2;' \
        -e 's;^# *\(stats_row_level *=\) *[^#]*\(#.*\);\1 on \2;' \
        -e 's;^# *\(autovacuum *=\) *[^#]*\(#.*\);\1 on \2;' \
        -e 's;^# *\(autovacuum_naptime *=\) *[^#]*\(#.*\);\1 1h \2;' \
        $RPM_BUILD_ROOT%{l_prefix}/share/postgresql/postgresql.conf.sample

    #   install run-command script
    %{l_shtool} mkdir -f -p -m 755 \
        $RPM_BUILD_ROOT%{l_prefix}/etc/rc.d
    %{l_shtool} install -c -m 755 %{l_value -s -a} \
        %{SOURCE rc.postgresxl} \
        $RPM_BUILD_ROOT%{l_prefix}/etc/rc.d/

    #   optionally strip down to client-only installation
%if "%{with_server}" != "yes"
    rm -f  $RPM_BUILD_ROOT%{l_prefix}/bin/pg_[a-bd-z]*
    rm -f  $RPM_BUILD_ROOT%{l_prefix}/bin/pg_c[a-np-z]*
    rm -f  $RPM_BUILD_ROOT%{l_prefix}/bin/pg_controldata
    rm -f  $RPM_BUILD_ROOT%{l_prefix}/bin/post*
    rm -f  $RPM_BUILD_ROOT%{l_prefix}/man/man1/pg_[a-bd-z]*
    rm -f  $RPM_BUILD_ROOT%{l_prefix}/man/man1/pg_c[a-np-z]*
    rm -f  $RPM_BUILD_ROOT%{l_prefix}/man/man1/pg_controldata.1
    rm -f  $RPM_BUILD_ROOT%{l_prefix}/man/man1/post*
    rm -rf $RPM_BUILD_ROOT%{l_prefix}/etc/rc.d
    rm -rf $RPM_BUILD_ROOT%{l_prefix}/include/postgresql/server
    rm -rf $RPM_BUILD_ROOT%{l_prefix}/lib/postgresql
    rm -rf $RPM_BUILD_ROOT%{l_prefix}/share/postgresql
    rm -rf $RPM_BUILD_ROOT%{l_prefix}/var/postgresql
%endif

    #   determine installation files
    %{l_rpmtool} files -v -ofiles -r$RPM_BUILD_ROOT \
%if "%{with_server}" == "yes"
        %{l_files_std} \
        '%attr(700,%{l_rusr},%{l_rgrp}) %dir %{l_prefix}/var/postgresql/db' \
        '%attr(755,%{l_rusr},%{l_rgrp}) %dir %{l_prefix}/var/postgresql/run'
%else
        %{l_files_std}
%endif

%files -f files

%clean

%pre
%if "%{with_server}" == "yes"
    #   before upgrade, check migration dump, save status and stop service
    [ $1 -eq 2 ] || exit 0
    if [ -f $RPM_INSTALL_PREFIX/var/postgresql/db/PG_VERSION -a \
         -f $RPM_INSTALL_PREFIX/bin/pg_migrate ]; then
        #   database migration dumping hint
        v_old_all=`cat $RPM_INSTALL_PREFIX/var/postgresql/db/PG_VERSION`
        v_old_maj=`echo "$v_old_all" | sed -e 's/^\([0-9]*\.[0-9]*\).*/\1/'`
        v_new_all="%{V_postgresxl}"
        v_new_maj=`echo "$v_new_all" | sed -e 's/^\([0-9]*\.[0-9]*\).*/\1/'`
        if [ ".$v_old_maj" != ".$v_new_maj" ]; then
            ( echo "You are upgrading from PostgresXL $v_old_all to PostgresSQL $v_new_all,"
              echo "which is a major version change. We expect a database incompatibility,"
              echo "so a full database backup and restore is required!"
            ) | %{l_rpmtool} msg -b -t notice
            if [ ".$RPM_POSTGRESQL_MIGRATE" != .ignore ]; then
                if [ ! -f $RPM_INSTALL_PREFIX/var/postgresql/db.dump.sql.bz2 ]; then
                    ( echo "We are performing a full backup of your existing database"
                      echo "($RPM_INSTALL_PREFIX/var/postgresql/db/) for you by running:"
                      echo "    \$ $RPM_INSTALL_PREFIX/bin/pg_migrate dump"
                      echo "If this fails for some reasons, try to dump your data manually:"
                      echo "    \$ $RPM_INSTALL_PREFIX/bin/pg_dumpall -U postgresql -o | \\ "
                      echo "      $RPM_INSTALL_PREFIX/lib/openpkg/bzip2 -9 \\ "
                      echo "      >$RPM_INSTALL_PREFIX/var/postgresql/db.dump.sql.bz2"
                      echo "Alternatively, if you want to force this package to be installed without"
                      echo "a previously created database dump, run the following command"
                      echo "before trying this package upgrade again:"
                      echo "    \$ RPM_POSTGRESQL_MIGRATE=ignore; export RPM_POSTGRESQL_MIGRATE"
                    ) | %{l_rpmtool} msg -b -t notice
                    $RPM_INSTALL_PREFIX/bin/pg_migrate dump
                    if [ $? -ne 0 ] || [ ! -f $RPM_INSTALL_PREFIX/var/postgresql/db.dump.sql.bz2 ]; then
                        ( echo "Automatic database dump creation failed!"
                          echo "PLEASE INVESTIGATE MANUALLY YOURSELF!"
                        ) | %{l_rpmtool} msg -b -t error
                        exit 1
                    fi
                fi
            fi
        fi
    fi
    eval `%{l_rc} postgresql status 2>/dev/null | tee %{l_tmpfile}`
    %{l_rc} postgresql stop 2>/dev/null
    exit 0
%endif

%post
%if "%{with_server}" == "yes"
    l_pguser="postgresql"
    l_pgpass="postgresql"
    if [ $1 -eq 1 ]; then
        #   create initial database
        su - %{l_rusr} -c \
            "LC_CTYPE=C; export LC_CTYPE; umask 077; \
            rm -rf $RPM_INSTALL_PREFIX/var/postgresql/db/*; \
            echo $l_pgpass >$RPM_INSTALL_PREFIX/var/postgresql/run/pg_initdb.pw; \
            $RPM_INSTALL_PREFIX/bin/pg_initdb \
                --encoding=SQL_ASCII --locale=C --auth=md5 --username=$l_pguser \
                --pwfile=$RPM_INSTALL_PREFIX/var/postgresql/run/pg_initdb.pw \
                --pgdata=$RPM_INSTALL_PREFIX/var/postgresql/db; \
            rm -f $RPM_INSTALL_PREFIX/var/postgresql/run/pg_initdb.pw" 2>&1 | \
        $RPM_INSTALL_PREFIX/lib/openpkg/shtool prop \
            -p "Creating initial PostgresXL DB in $RPM_INSTALL_PREFIX/var/postgresql/db"
        if [ ! -f $RPM_INSTALL_PREFIX/var/postgresql/db/PG_VERSION ]; then
            echo "ERROR: failed to create initial PostgresXL database" 1>&2
            exit 1
        fi
        ( umask 077
          ( echo "##"
            echo "##  pg_superuser.conf -- PostgreSQL database superuser configuration"
            echo "##"
            echo ""
            echo "superuser_database=\"template1\""
            echo "superuser_username=\"$l_pguser\""
            echo "superuser_password=\"$l_pgpass\""
            echo ""
          ) >$RPM_INSTALL_PREFIX/var/postgresql/db/pg_superuser.conf
          chown %{l_rusr}:%{l_rgrp} $RPM_INSTALL_PREFIX/var/postgresql/db/pg_superuser.conf || exit $?
          chmod 600 $RPM_INSTALL_PREFIX/var/postgresql/db/pg_superuser.conf || exit $?
        ) || exit $?

        #   display information about next steps
        ( echo "An initial PostgresXL DB was created with the two standard"
          echo "databases 'template0' and 'template1'. The owner of both"
          echo "is the DB user '$l_pguser'. Its initial password is '$l_pgpass'."
          echo ""
          echo "After starting PostgresXL with"
          echo "    \$ $RPM_INSTALL_PREFIX/bin/openpkg rc postgresxl start"
          echo "you should immediately change this with the following command:"
          echo "    \$ $RPM_INSTALL_PREFIX/bin/pg_passwd postgresql template1"
          echo ""
          echo "Then you usually create a database for a user <user> (assuming that"
          echo "his home directory is /u/<user>) with password <password> under"
          echo "path /u/<user>/rdbms with the commands:"
          echo "    \$ mkdir /u/<user>/rdbms"
          echo "    \$ chmod 700 /u/<user>/rdbms"
          echo "    \$ chown %{l_rusr}:%{l_rgrp} /u/<user>/rdbms"
          echo "    \$ $RPM_INSTALL_PREFIX/bin/psql -U $l_pguser -d template1"
          echo "    template1=> CREATE ROLE <user>"
          echo "                LOGIN ENCRYPTED PASSWORD '<password>'"
          echo "                NOCREATEDB NOCREATEROLE;"
          echo "    template1=> CREATE TABLESPACE <user> OWNER <user>"
          echo "                LOCATION '/u/<user>/rdbms';"
          echo "    template1=> CREATE DATABASE <user> OWNER <user>"
          echo "                TABLESPACE <user>;"
          echo "    template1=> \\q"
          echo "    \$ echo 'localhost:*:<user>:<user>:<password>' >>/u/<user>/.pgpass"
          echo "    \$ chmod 600 <user> /u/<user>/.pgpass"
          echo "    \$ chown <user> /u/<user>/.pgpass"
          echo "After this the user <user> will be able to connect to his RDBMS with:"
          echo "    \$ $RPM_INSTALL_PREFIX/bin/psql"
        ) | %{l_rpmtool} msg -b -t notice
    fi

    if [ $1 -eq 2 ]; then
        #   after upgrade, restore status
        { eval `cat %{l_tmpfile}`; rm -f %{l_tmpfile}; true; } >/dev/null 2>&1
        [ ".$postgresql_active" = .yes ] && %{l_rc} postgresql start
        if [   -f $RPM_INSTALL_PREFIX/var/postgresql/db/PG_VERSION -a \
             ! -f $RPM_INSTALL_PREFIX/var/postgresql/db/pg_superuser.conf ]; then
            ( umask 077
              ( echo "##"
                echo "##  pg_superuser.conf -- PostgreSQL database superuser configuration"
                echo "##"
                echo ""
                echo "superuser_database=\"template1\""
                echo "superuser_username=\"$l_pguser\""
                echo "superuser_password=\"\""
                echo ""
              ) >$RPM_INSTALL_PREFIX/var/postgresql/db/pg_superuser.conf
              chown %{l_rusr}:%{l_rgrp} $RPM_INSTALL_PREFIX/var/postgresql/db/pg_superuser.conf || exit $?
              chmod 600 $RPM_INSTALL_PREFIX/var/postgresql/db/pg_superuser.conf || exit $?
            ) || exit $?
            ( echo "Created still missing \"pg_superuser.conf\" configuration file."
              echo "You should update its content by resetting the PostgresXL"
              echo "superuser account password with the following command:"
              echo "    \$ $RPM_INSTALL_PREFIX/bin/pg_passwd postgresql template1"
            ) | %{l_rpmtool} msg -b -t warn
        fi
        if [ -f $RPM_INSTALL_PREFIX/var/postgresql/db/PG_VERSION -a ".$PG_MIGRATE" != .ignore ]; then
            #   database migration restoring hint
            v_old_all=`cat $RPM_INSTALL_PREFIX/var/postgresql/db/PG_VERSION`
            v_old_maj=`echo "$v_old_all" | sed -e 's/^\([0-9]*\.[0-9]*\).*/\1/'`
            v_new_all="%{V_postgresxl}"
            v_new_maj=`echo "$v_new_all" | sed -e 's/^\([0-9]*\.[0-9]*\).*/\1/'`
            if [ ".$v_old_maj" != ".$v_new_maj" ]; then
                ( echo "You upgraded from PostgresXL $v_old_all to PostgressXL $v_new_all,"
                  echo "which is a major version upgrade. We expect a database incompatibility,"
                  echo "so we strongly recommend you to recreate the existing database under"
                  echo "$RPM_INSTALL_PREFIX/var/postgresql/db/ by running the following command:"
                  echo "    \$ $RPM_INSTALL_PREFIX/bin/pg_migrate restore"
                  echo "If this fails for some reasons, try to restore your data manually:"
                  echo "    \$ $RPM_INSTALL_PREFIX/lib/openpkg/bzip2 -d -c \\ "
                  echo "      $RPM_INSTALL_PREFIX/var/postgresql/db.dump.sql.bz2 | \\ "
                  echo "      $RPM_INSTALL_PREFIX/bin/psql -U postgresql -d template1"
                ) | %{l_rpmtool} msg -b -t warn
            fi
        fi
    fi
    exit 0
%endif

%preun
%if "%{with_server}" == "yes"
    #   before erase, stop service and remove log files
    [ $1 -eq 0 ] || exit 0
    %{l_rc} postgresql stop 2>/dev/null
    rm -f $RPM_INSTALL_PREFIX/var/postgresql/run/* >/dev/null 2>&1 || true
    #   optionally unlink from ODBC
    exit 0
%endif

