#!/bin/sh
##
##  pg_migrate -- PostgreSQL Database Migration Utility
##  Copyright (c) 2007-2018 Ralf S. Engelschall <http://engelschall.com/>
##
##  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.
##

#   configuration
l_prefix="@l_prefix@"
l_rusr="@l_rusr@"
l_rgrp="@l_rgrp@"

#   load superuser information
l_pgdata=""
l_pguser=""
l_pgpass=""
if [ ! -r $l_prefix/var/postgresql/db/pg_superuser.conf ]; then
    echo "$0:ERROR: unable to read file \"$l_prefix/var/postgresql/db/pg_superuser.conf\" (use pg_passwd(1) to create)" 1>&2
    exit 1
fi
eval `. $l_prefix/var/postgresql/db/pg_superuser.conf; \
      echo l_pgdata=\"$superuser_database\"; \
      echo l_pguser=\"$superuser_username\"; \
      echo l_pgpass=\"$superuser_password\"`

#   establish sane environment
LC_CTYPE=C
export LC_CTYPE
umask 022

#   check command line
if [ $# -ne 1 -a $# -ne 2 ]; then
    echo "$0:ERROR: invalid command line" 1>&2
    echo "$0:USAGE: $0 dump|restore [<password>]" 1>&2
    exit 1
fi
cmd="$1"; shift
if [ $# -eq 1 ]; then
    l_pgpass="$1"; shift
fi

#   dispatch into commands
case $cmd in
    dump )
        echo "++ enforcing full-superuser access policy"
        cp -p $l_prefix/var/postgresql/db/pg_hba.conf \
              $l_prefix/var/postgresql/db/pg_hba.conf.orig
        ( echo "local all all trust"
          echo "host all all 127.0.0.1/32 trust"
        ) >$l_prefix/var/postgresql/db/pg_hba.conf

        ( eval `${l_prefix}/bin/openpkg rc postgresql status 2>/dev/null`
          echo "postgresql_active=\"$postgresql_active\""
        ) 2>/dev/null
        if [ ".$postgresql_active" = .yes ]; then
            echo "++ reloading already running database engine"
            $l_prefix/bin/openpkg rc postgresql reload
            sleep 2
            epilog=reload
        else
            echo "++ temporarily starting database engine"
            $l_prefix/bin/openpkg rc postgresql start
            sleep 4
            epilog=stop
        fi

        echo "++ rotating dump files $l_prefix/var/postgresql/db.dump*.sql.bz2"
        i=9
        rm -f $l_prefix/var/postgresql/db.dump.$i.sql.bz2 >/dev/null 2>&1 || true
        while [ $i -gt 0 ]; do
            j=$i
            i=`expr $i - 1`
            if [ $i -eq 0 ]; then
                prev="$l_prefix/var/postgresql/db.dump.sql.bz2"
                next="$l_prefix/var/postgresql/db.dump.$j.sql.bz2"
            else
                prev="$l_prefix/var/postgresql/db.dump.$i.sql.bz2"
                next="$l_prefix/var/postgresql/db.dump.$j.sql.bz2"
            fi
            if [ -f $prev ]; then
                mv $prev $next
            fi
        done

        echo "++ dumping all databases into $l_prefix/var/postgresql/db.dump.sql.bz2"
        PGPASSWORD="$l_pgpass" \
        $l_prefix/bin/pg_dumpall \
            -U "$l_pguser" -o |\
            $l_prefix/lib/openpkg/bzip2 -9 \
                >$l_prefix/var/postgresql/db.dump.sql.bz2
        chown ${l_rusr}:${l_rgrp} $l_prefix/var/postgresql/db.dump.sql.bz2
        chmod 700 $l_prefix/var/postgresql/db.dump.sql.bz2

        echo "++ restoring original access policy"
        cp -p $l_prefix/var/postgresql/db/pg_hba.conf.orig \
              $l_prefix/var/postgresql/db/pg_hba.conf
        rm -f $l_prefix/var/postgresql/db/pg_hba.conf.orig

        if [ ".$epilog" = .reload ]; then
            echo "++ reloading already running database engine (again)"
            $l_prefix/bin/openpkg rc postgresql reload
            sleep 2
        else
            echo "++ stopping temporarily started database engine"
            $l_prefix/bin/openpkg rc postgresql stop
            sleep 4
        fi
        ;;

    restore )
        if [ ".`$l_prefix/bin/openpkg rc postgresql status 2>&1 | grep 'is running'`" != . ]; then
            echo "++ stopping already running database engine"
            $l_prefix/bin/openpkg rc postgresql stop
            sleep 2
            epilog=start
        else
            epilog=none
        fi

        echo "++ rotating database directories $l_prefix/var/postgresql/db.old*/"
        i=9
        rm -rf $l_prefix/var/postgresql/db.old.$i >/dev/null 2>&1 || true
        while [ $i -gt 0 ]; do
            j=$i
            i=`expr $i - 1`
            if [ $i -eq 0 ]; then
                prev="$l_prefix/var/postgresql/db"
                next="$l_prefix/var/postgresql/db.old.$j"
            else
                prev="$l_prefix/var/postgresql/db.old.$i"
                next="$l_prefix/var/postgresql/db.old.$j"
            fi
            if [ -d $prev ]; then
                mv $prev $next
            fi
        done

        echo "++ creating new database directory $l_prefix/var/postgresql/db/"
        mkdir $l_prefix/var/postgresql/db
        chown ${l_rusr}:${l_rgrp} $l_prefix/var/postgresql/db
        chmod 700 $l_prefix/var/postgresql/db

        su - ${l_rusr} -c \
            "LC_CTYPE=C; export LC_CTYPE; umask 022; \
            echo $l_pgpass >$l_prefix/var/postgresql/run/pw; \
            $l_prefix/bin/pg_initdb \
                -U $l_pguser --pwfile=$l_prefix/var/postgresql/run/pw \
                -D $l_prefix/var/postgresql/db; \
            rm -f $l_prefix/var/postgresql/run/pw" 2>&1 |\
        $l_prefix/lib/openpkg/shtool prop \
            -p "++ creating new database data"

        echo "++ restoring database configurations"
        for conf in pg_hba.conf pg_ident.conf postgresql.conf; do
            cp -p $l_prefix/var/postgresql/db.old.1/$conf \
                  $l_prefix/var/postgresql/db/
        done

        echo "++ enforcing full-superuser access policy"
        cp -p $l_prefix/var/postgresql/db/pg_hba.conf \
              $l_prefix/var/postgresql/db/pg_hba.conf.orig
        ( echo "local all all trust"
          echo "host all all 127.0.0.1/32 trust"
        ) >$l_prefix/var/postgresql/db/pg_hba.conf

        if [ ".$epilog" = .start ]; then
            echo "++ starting database engine"
        else
            echo "++ temporarily starting database engine"
        fi
        $l_prefix/bin/openpkg rc postgresql start
        sleep 4

        echo "++ restoring all databases from $l_prefix/var/postgresql/db.dump.sql.bz2"
        $l_prefix/lib/openpkg/bzip2 -c -d \
            $l_prefix/var/postgresql/db.dump.sql.bz2 |\
                $l_prefix/bin/psql -U "$l_pguser" -d "$l_pgdata" 2>&1 |\
                    tee $l_prefix/var/postgresql/db.log |\
                        $l_prefix/lib/openpkg/shtool prop \
                            -p "++ restoring data (see $l_prefix/var/postgresql/db.log)"

        echo "++ restoring original access policy"
        cp -p $l_prefix/var/postgresql/db/pg_hba.conf.orig \
              $l_prefix/var/postgresql/db/pg_hba.conf
        rm -f $l_prefix/var/postgresql/db/pg_hba.conf.orig

        if [ ".$epilog" = .start ]; then
            echo "++ reloading already running database engine"
            $l_prefix/bin/openpkg rc postgresql reload
            sleep 2
        else
            echo "++ stopping temporarily started database engine"
            $l_prefix/bin/openpkg rc postgresql stop
            sleep 4
        fi
        ;;
    * )
        echo "$0:ERROR: unknown command \"$cmd\"" 1>&2
        exit 1
        ;;
esac

