#!/bin/bash

_debug() {
        if [ -n "${DEBUG}" ]
        then
                echo "DEBUG:   $1" >&2
                shift
                for text in "$@"
                do
                        echo "         ${text}" >&2
                done
        fi
}

_quit() {
    echo $@
    exit 1
}

WinStrom_detectPostgresql() {
    # /etc/init.d doesn't have to contain everything, e.g. when using systemd
    # and we should be using "service" anyway
    SERVICE="/etc/init.d/"
    if [ -f /sbin/service ]; then
        SERVICE="/sbin/service "
    else
        if [ -f /usr/sbin/service ]; then
            SERVICE="/usr/sbin/service "
        fi
    fi

    # Default values
    PG_USER=postgres
    PG_GROUP=postgres
    PG_PORT=5434
    CLUSTERARG=""


    # Detect PostgreSQL version.
    DBVERSION=0
    if [ -d /usr/lib/postgresql/9.2/ -o -d /usr/pgsql-9.2/ ]; then
        DBVERSION=9.2
    else 
        if [ -d /usr/lib/postgresql/9.1/ -o -d /usr/pgsql-9.1/ ]; then
            DBVERSION=9.1
        else 
            if [ -d /usr/lib/postgresql/9.0/ -o -d /usr/pgsql-9.0/ ]; then
                DBVERSION=9.0
            else 
                if [ -d /usr/lib/postgresql/8.4/ -o -d /usr/pgsql-8.4/ ]; then
                    DBVERSION=8.4
                else 
                    if [ -d /usr/lib/postgresql/8.3/ -o -d /usr/pgsql-8.3/ ]; then
                        DBVERSION=8.3
                    else 
                        if [ -d /usr/lib/postgresql/8.2/ -o -d /usr/pgsql-8.2/ ]; then
                            DBVERSION=8.2
                        else 
                            # Fallback to psql - it can be a problem when used with clusters (ie can have multiple versions installed at once).
                            DBVERSION=`psql --version | head -n 1 | cut "-d " -f 3 | cut -d. -f 1-2`
                        fi
                    fi
                fi
            fi
        fi
    fi

    # Detect Cluster support (Debian/Ubuntu specific)
    HAS_CLUSTERS=0
    if [ -f /usr/bin/pg_lsclusters ]; then
        HAS_CLUSTERS=1
    fi

    # check if PostgreSQL is running or start it
    if [ "x$HAS_CLUSTERS" = "x1" ]; then
        # check for cluster existance
        CLUSTERNAME=flexibee
        EXISTING=0
        /usr/bin/pg_lsclusters  | grep -e winstrom -e flexibee 2>/dev/null > /dev/null && EXISTING=1
        if [ "x$EXISTING" = "x0" ]; then
            CLUSTERNAME=`/usr/bin/pg_lsclusters --no-head | grep $DBVERSION | head -n 1 | cut -c 9-18 | sed "s/[[:space:]]*//g" | head -1`
	    else
            # it is running with the old name?
            /usr/bin/pg_lsclusters  | grep -e winstrom 2>/dev/null > /dev/null && CLUSTERNAME=winstrom
        fi

        RUNNING=0
        # Cluster version
        /usr/bin/pg_lsclusters | grep $CLUSTERNAME | grep online 2> /dev/null > /dev/null && RUNNING=1

        # In case the cluster already existed, we need to fetch it's real PostgreSQL version
        DBVERSION=`/usr/bin/pg_lsclusters  | grep $CLUSTERNAME | cut "-d " -f 1 | sed "s/[[:space:]]*//g" | head -1`
        PG_PORT=`/usr/bin/pg_lsclusters  | grep $CLUSTERNAME | cut -c 19-23 | sed "s/[[:space:]]*//g" | head -1`

        CLUSTERARG="--cluster $DBVERSION/$CLUSTERNAME"
        CONFIGFILE=/etc/postgresql/$DBVERSION/$CLUSTERNAME/postgresql.conf
        PG_HBA_FILE=/etc/postgresql/$DBVERSION/$CLUSTERNAME/pg_hba.conf
    
        _debug "Found cluster $CLUSTERARG"

        START_COMMAND="/usr/bin/pg_ctlcluster $DBVERSION $CLUSTERNAME "
        START_COMMAND2="/etc/init.d/postgresql-$DBVERSION "

        if [ ! -f $START_COMMAND2 ]; then
            START_COMMAND2="${SERVICE}postgresql"
        fi

    else
        # Normal PostgreSQL version
        RUNNING=0
        CREATED=0
        NEED_RESTART=0
        PG_SERVICE="/etc/init.d/postgresql"
        if [ -f /etc/init.d/postgresql-$DBVERSION ]; then
          PG_SERVICE="/etc/init.d/postgresql-$DBVERSION"
        fi
        $PG_SERVICE status  2> /dev/null > /dev/null && RUNNING=1

    	if [ "x$RUNNING" = "x1" ]; then
    	    # Hack for Mandriva - it returns always 1
            $PG_SERVICE status | grep -E "(stopped|zastaven)" > /dev/null && RUNNING=0
        fi

        if [ "x$RUNNING" = "x0" ] && { [ -f /etc/init.d/postgresql ] || [ -f /etc/init.d/postgresql-$DBVERSION ]; } then
            # On some distribution (Fedora, ...) PostgreSQL is not initialized after installation. We must call '/etc/init.d/postgresql initdb'
            HAS_INITDB=0
            $PG_SERVICE --help | grep initdb > /dev/null && HAS_INITDB=1

            if [ -d /var/lib/pgsql/data ]; then        
                if [ ! -f /var/lib/pgsql/data/PG_VERSION ]; then
                    if [ "x$HAS_INITDB" = "x1" ]; then
                        $PG_SERVICE initdb || _quit "Can't initialize PostgreSQL"
                        CREATED=1
                    else
                        $PG_SERVICE start || _quit "Can't initialize PostgreSQL"
                        RUNNING=1
                    fi
                fi
            fi
            if [ -d /var/lib/pgsql/$DBVERSION/data ]; then
                if [ ! -f /var/lib/pgsql/$DBVERSION/data/PG_VERSION ]; then
                    if [ "x$HAS_INITDB" = "x1" ]; then
                        $PG_SERVICE initdb || _quit "Can't initialize PostgreSQL"
                        CREATED=1
                    else
                        $PG_SERVICE start || _quit "Can't initialize PostgreSQL"
                        RUNNING=1
                    fi
                fi
            fi
        fi

        # Fedora 16 (and possibly others?) has special script for initdb, can't do it with "service postgresql"
        if [ "x$RUNNING" = "x0" -a -f /usr/bin/postgresql-setup ]; then
            if [ ! -f /var/lib/pgsql/data/PG_VERSION ]; then
                /usr/bin/postgresql-setup initdb || _quit "Can't initialize PostgreSQL"
                CREATED=1
            fi
        fi

        # we need to find correct port. So we need PostgreSQL configuration
        CONFIGFILE=/etc/postgresql/postgresql.conf
        PG_HBA_FILE=/etc/postgresql/pg_hba.conf
        if [ -f /var/lib/pgsql/data/postgresql.conf ]; then
            CONFIGFILE=/var/lib/pgsql/data/postgresql.conf
            PG_HBA_FILE=/var/lib/pgsql/data/pg_hba.conf
        fi
        if [ -f /var/lib/pgsql/$DBVERSION/data/postgresql.conf ]; then
            CONFIGFILE=/var/lib/pgsql/$DBVERSION/data/postgresql.conf
            PG_HBA_FILE=/var/lib/pgsql/$DBVERSION/data/pg_hba.conf
        fi
        if [ -f /var/lib/postgresql/data/postgresql.conf ]; then 
            CONFIGFILE=/var/lib/postgresql/data/postgresql.conf
    	    PG_HBA_FILE=/var/lib/postgresql/data/pg_hba.conf
        fi
        if [ -f /var/lib/postgresql/$DBVERSION/data/postgresql.conf ]; then 
            CONFIGFILE=/var/lib/postgresql/$DBVERSION/data/postgresql.conf
            PG_HBA_FILE=/var/lib/postgresql/$DBVERSION/data/pg_hba.conf
        fi

        PG_PORT=`cat $CONFIGFILE | grep port | cut -d# -f 1 | cut -d= -f 2 | sed "s/[[:space:]]*//g"`
        # Trim spaces
	PG_PORT=$(echo $PG_PORT | sed 's/ *$//g' | sed 's/^ *//g')
        if [ "x$PG_PORT" = "x" ]; then
	    PG_PORT=5432
        fi

        START_COMMAND="${SERVICE}postgresql "
        if [ -f /etc/init.d/postgresql-$DBVERSION ]; then
          START_COMMAND="${SERVICE}postgresql-$DBVERSION "
        fi
    fi    
}

WinStrom_detectRunning() {
    SUFF=$1
    RUNNING=0
    if [ -f $FLEXIBEE_PID$SUFF ]; then
	    ps `cat $FLEXIBEE_PID$SUFF` >/dev/null && RUNNING=1 || true
    fi
    return 0
}



WinStrom_startIfNeeded() {
    R=$1

    # Start PostgreSQL
    if [ "x$R" = "x0" ]; then
        _debug "Starting PostgreSQL"
        OK=1
        $START_COMMAND start 2> /dev/null || OK=0
        if [ "x$OK" == "x0" -a "x$START_COMMAND2" != "x" ]; then
	    $START_COMMAND2 start  2> /dev/null && OK=1
        fi

        if [ "x$OK" == "x0" ]; then
	    _quit "Can't start PostgreSQL"
        fi
    fi
}
