# New Yaim Configuration and setup for D-Cache 1.6.6-X 1.7.0, 1.7.1, and 1.8.0
# Maintained by Owen Synge on behalf of Dcache
# Based upon work by 
# M Litmaath, M de Riese, J Mencak, J Novak,L Poncent, O Keeble, L Field and M Aart
# which based thier work upon d-cache configuration adapted 
# from package d-cache-lcg

# GridPP's testing has been very useful

# This script is based upon earlier work by LHC


# Used variables
# Obligatory: DCACHE_ADMIN=admin_host
#             DCACHE_POOLS="pool_node1:[size:]/pool_path1 pool_node2:[size:]/pool_path2"
#             <size> ::= [0-9]*
# Optional:   DCACHE_PNFS_SERVER=pnfs_host
# Optional:   DCACHE_PORT_RANGE="20000,25000"
# Optional:   DCACHE_DOOR_SRM="pool_node1[:port]"
#          Defaults to Admin nodes
# Optional:   DCACHE_DOOR_GSIFTP="pool_node1[:port] pool_node2[:port]"
#          Defaults to Door nodes
# Optional:   DCACHE_DOOR_GSIDCAP="pool_node1[:port] pool_node2[:port]"
#          Defaults to Door nodes
# Optional:   DCACHE_DOOR_DCAP="pool_node1[:port] pool_node2[:port]"
#          Defaults to Door nodes


# Set this to wipe the postgres databases
# Optional:RESET_DCACHE_RDBMS=yes
#
# Set this to reset the PNFS server
# Optional:RESET_DCACHE_PNFS=yes
#
# Set this to reset the D-cache configuration
# Optional:RESET_DCACHE_CONFIGURATION=yes


# Structure of this script

# Yaim utility functions come first in this script, these are placed 
# here to avoid dependacy issues as these are functions that will be 
# Needed by many components, D-Cache in particular makes use of 
# these utilities



# functions starting yaim_query_conf

# This script was always designed as a way to make modification easy
# To this end set up questions are placed at the top of the file. This
# is intended to make porting Yaim to debconf or any other cluster wide 
# management system easy. These functions are queries that could in 
# practice be queries to an interactive installer or a cluster 
# management system

#
# functions starting yaim_state

# These functions are to establish the state of the install and direct 
# what components are to be installed. They do not change the state 
# of uninstalled/installed components





# Set this to wipe the postgres databases
# Optional:RESET_DCACHE_RDBMS=yes

# These functions confiugure D-cache and components

yaim_query_conf_file_path_postgres_home()
{
RET=""
if [ -z "$POSTGRESQL_HOME" ] ; then
    RET=/var/lib/pgsql
else
    RET="$POSTGRESQL_HOME"
fi
}

yaim_query_conf_file_path_postgres_log()
{
RET=""

if [ -z "$POSTGRESQL_LOG" ] ; then
    yaim_query_conf_file_path_postgres_home
    RET=${RET}/pgstartup.log    
else
    RET="$POSTGRESQL_LOG"
fi
}


# Yaim utility functions start

# Returns RET in the form of Major.Minor.Revision
# Examples form tested versions include 8.1.3 and 8.0.4
# return code is 1 on error
yaim_state_postgresql_version() 
{
    local creatuserpath
    local versionstring
    RET=""
    creatuserpath=$(which psql 2> /dev/null )
    if [ -z ${creatuserpath} ] ; then
        echo WARNING: Could not find the createuser comman in the path
        echo WARNING: Postgresql client tools may not be installed
        return 1
    fi
    versionstring=$(${creatuserpath} --version)
	if [ $? != 0 ] ; then
        return 1
    fi
    RET=$(echo ${versionstring} | cut -d" " -f3)
    return 0
}

yaim_state_postgresql_started() 
{
	su postgres -c "psql  -l " > /dev/null 2>&1
	return $?
}


yaim_state_postgresql_database_installed() 
{
	RET=$(psql -U postgres -l | grep  "|" | grep -v Name | cut -d"|" -f1)
}

yaim_state_postgresql_users_installed() 
{
	RET=$(psql  -U postgres template1 -c "select * from pg_user;" | grep  "|" | grep -v Name | cut -d"|" -f1)
}

yaim_state_reset_postgresql() 
{
yaimlog DEBUG "function yaim_state_reset_postgresql start"
  # Returns 0 when postgres is fine
  # Returns 1 when postgres should be removed
  local result
  local rcrmpnfs
  result=0
  if [ "X$RESET_DCACHE_RDBMS" == Xyes ] ; then
    result=1
  fi
yaimlog DEBUG "function yaim_state_reset_postgresql stop"
  return $result
}

create_postgresql_database()
{
	local DATABASE
	local DEFINITION
	local EXTRAPARAMS
	local rdbmsstarted
	local ret
	
	DATABASE=$1
	DEFINITION=$2
	EXTRAPARAMS=""
	if [ "X$DATABASE" == "X" ] ; then
		echo "Postgres database name not given"
		echo "Bailing out!"
		exit 3
	fi
	yaim_state_postgresql_started
	rdbmsstarted=$?
	if [ "X$rdbmsstarted" != "X0" ] ; then
		echo "Postgres not starting so database creation failed"
		echo "Bailing out!"
		exit 3
	fi

	if test "X${DEFINITION}" != X
		then
		if ! test -f ${DEFINITION}
		then
			echo "Definition file does not exist"
		exit 1
		fi
		EXTRAPARAMS="-f ${DEFINITION}"
	fi
	echo createdb -U srmdcache $DATABASE
	createdb -U srmdcache $DATABASE  > /dev/null
	ret=$?
	if [ "X$ret" != "X0" ] ; then
		echo "Postgres Command 'createdb -U srmdcache $DATABASE' failed"
		echo "Bailing out!"
		exit 3
	fi
	if [ "X$EXTRAPARAMS" != "X" ] ; then
		psql -U srmdcache $DATABASE  $EXTRAPARAMS 2>&1 > /dev/null
		ret=$?
		if [ "X$ret" != "X0" ] ; then
			echo "Postgres Command 'psql -U srmdcache $DATABASE  $EXTRAPARAMS' failed"
			echo "Bailing out!"
			exit 3
		fi
	fi	
}

config_pgsql_base_init()
{
    yaimlog DEBUG "function config_pgsql_base_init start"
    local PGENGINE
    local PGPORT
    local SU
    PGENGINE=/usr/bin
    PGPORT=5432

    # For some reason DESY /dev/null on test computers is 
    # not set with permisions 666 but with permisions 600
    NULL_PERM=$(stat -c %a  /dev/null )
    if [ "${NULL_PERM}" -ne "666"  ] ; then
        chmod 666 /dev/null
    fi

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


    echo -n $"Initializing database: "
    yaim_query_conf_file_path_postgres_home
    pgdata=$RET
    if [ ! -e "$pgdata" -a ! -h "$pgdata" ]
    then
        mkdir -p "$pgdata" || exit 1
        chown postgres:postgres "$pgdata"
        chmod go-rwx "$pgdata"
    fi
    yaim_query_conf_file_path_postgres_log
    pglog=$RET
    pglogdir=$(dirname ${pglog})
    if [ ! -e "$pglogdir" -a ! -h "$pglogdir" ]
    then
        mkdir -p "$pglogdir" || exit 1
        chown postgres:postgres "$pglogdir"
        chmod go-rwx "$pglogdir"
    fi
    # Clean up SELinux tagging for pgdata
    [ -x /sbin/restorecon ] && /sbin/restorecon "$pgdata"
    /etc/init.d/postgresql start
    startedOK=$?
    if [ "$startedOK" != 0 ] ; then
        echo $pglogdir
        service postgresql initdb
    fi
    # Initialize the database
    $SU -l postgres -c " $PGENGINE/initdb --pgdata='$pgdata' --auth='ident sameuser' " >> "$pglog" 2>&1 < /dev/null
    # Create directory for postmaster log
    mkdir "$pgdata/pg_log"
    chown postgres:postgres "$pgdata/pg_log"
    chmod go-rwx "$pgdata/pg_log"
    if [ ! -f "$pgdata/data/PG_VERSION" ] ; then
        echo ERROR: file $pgdata/data/PG_VERSION not found indicating Postgresql has failed to initialize.
        echo ERROR: or that \$POSTGRESQL_HOME is set to the wrong value.
        exit 1
    fi
}

config_pgsql_base_access() 
{
yaimlog DEBUG "function config_pgsql_base_access start"
######################################################################
# Postgres configuration script from d-cache-lcg
######################################################################
local db_dir
local data_dir
local conf1
local tmp1
local conf2
local tmp2
local hostname
local ip0
local ip1
local ip2
local local_trust
local hosts_trust
local AWK
local rdbmsstarted
db_dir=/var/lib/pgsql
data_dir=$db_dir/data

# Enable network access in postgres config file (default port 5432 is used)

conf1=$data_dir/postgresql.conf
tmp1=$conf1.tmp

conf2=$db_dir/data/pg_hba.conf
tmp2=$conf2.tmp

# Allow hosts to connect to the DB

hostname=`hostname -f`
ip0='               '
ip1='127.0.0.1      '
ip2=`host $hostname | awk '{ printf "%-15s", $NF }'`
local_trust="
local   all         all         $ip0                     trust
"
hosts_trust="
host    all         all         $ip1   255.255.255.255   trust
host    all         all         $ip2   255.255.255.255   trust
"

#echo local_trust=${local_trust}
#echo hosts_trust=${hosts_trust}
AWK="
    /^#?local .*$/ {
	print local_trust
	next
    }
    /^#?host .*$/ {
	print hosts_trust
	next
    }
    {
	print
    }
"

# Start PostgreSQL
/etc/init.d/postgresql stop
/etc/init.d/postgresql start
sleep 3
yaim_state_postgresql_started
rdbmsstarted=$?
if [ "X$rdbmsstarted" != "X0" ] ; then
	echo "Postgres not starting as database Access failed"
	echo "Bailing out!"
	exit 3
fi

#
# Note that the following command runs the following section as user postgres
#

su - postgres -c "
cd  # ensure cwd is accessible

sed 's/^# *tcpip_socket *=.*/tcpip_socket = true/' $conf1 > $tmp1 &&
    mv $tmp1 $conf1

awk \"$AWK\" local_trust=\"$local_trust\" hosts_trust=\"$hosts_trust\" $conf2 > \
    $tmp2 && mv $tmp2 $conf2

# Make PostgreSQL re-read 'pg_hba.conf' (Client Authentication Configuration File)
killall -HUP postmaster
"

#
# Note the section as user postgres finished
#

# Automatic startup on reboot
chkconfig --level 2345 postgresql on
yaimlog DEBUG "function config_pgsql_base_access stop"
}




yaim_query_conf_node_dcache_dbserver_create_list()
{
    # Returns 0 when node is not srm_door node
    # Returns 1 when node is srm_door node
    # "dcache" "companion"  "replicas"  "billing"
    local holder
    local result
    local rcadmin
    local holder
    local rcpnfss
    local rcsrm
    
    RET=""
    holder=""
    result=0
    yaim_query_conf_node_dcache_admin
    rcadmin=$?
    if [ "$rcadmin" == 1 ] ; then
        holder="dcache replicas  billing $holder"
    fi
    yaim_query_conf_node_dcache_pnfsserver
    rcpnfss=$?
    if [ "$rcpnfss" == 1 ] ; then
        holder="companion $holder"
    fi
    yaim_query_conf_node_srm_door
    rcsrm=$?
    if [ "$rcsrm" == 1 ] ; then
        holder="dcache $holder"
    fi
    for i in $holder
    do
        if [ -z "$(echo $RET | grep $i)" ] ; then
            RET="$RET $i"
        fi
    done
    return 0
}


check_postgresql_database_all()
{
    local pginstalledrdbms
    local DCACHE_DATABASES
    local INSTALLED
    local check_postgresql_databaserc

    yaim_state_postgresql_database_installed
    pginstalledrdbms=${RET}
    yaim_query_conf_node_dcache_dbserver_create_list
    DCACHE_DATABASES=$RET
    for RDBMS in $DCACHE_DATABASES
    do
        yaimlog INFO "Checking for the RDBMS '$RDBMS'"
        INSTALLED=$(echo ${pginstalledrdbms} |  grep "${RDBMS}" )
        if [ "X" = "X${INSTALLED}" ] ; then
            yaimlog INFO "Could not find '$RDBMS' so installing"
            case "${RDBMS}" in
                "companion")
                    create_postgresql_database $RDBMS ${INSTALL_ROOT}/d-cache/share/pnfs/psql_install_companion.sql
                ;;      
                "replicas")
                    create_postgresql_database $RDBMS ${INSTALL_ROOT}/d-cache/share/replica/psql_install_replicas.sql
                ;;
                * )
                    create_postgresql_database $RDBMS
                ;;
            esac
            check_postgresql_databaserc=$?

            if test $check_postgresql_databaserc != 0
                then 
                if test $check_postgresql_databaserc = 2
                    then
                        yaimlog INFO "DataBase $RDBMS exists"
                    else
                        yaimlog ABORT "Data Base must be created"
                        exit 1
                fi
            fi
        fi
    done
}




# this function installs users within the postgresql system
# The first parameter is always the user to add
# It takes an optional and unlimited number of parametes in key vlaue form
# so far supported values the last instance overrides previous values
# The list of key value pairs are as follows
# createrole=no/yes
config_pgsql_base_user() 
{
	local USER
	local rc
    yaimlog DEBUG "function config_pgsql_base_user start $1"
	USER=$1
	if [ -z "$USER" ] ; then
		echo "config_pgsql_base_user failed as no user given"
		exit 2
	fi

	# Try to create user
	createuser -U postgres --no-adduser -r --createdb $USER
	rc=$?
	#try to escape problems on old postgresql 8.0 systems
	if [ ! "$rc" == 0 ] ;  then
		# Try to create user without the -r option
		# which is not supported on postgres 8.0.4
		createuser -U postgres --no-adduser --createdb $USER
		rc=$?
		if [ ! "$rc" == 0 ] ;  then
			echo "createuser -U postgres --no-adduser --createdb $USER"
			echo "Command failed"
			exit 1	
		fi
	fi
	yaimlog DEBUG "function config_pgsql_base_user stop"
}

# This function only installs users which are not already installed.
# Users are gived as parameters to this function
config_pgsql_base_users()
{
    yaimlog DEBUG "function config_pgsql_base_users start"
	local pgsql_current_users
	local USER
	local present
	pgsql_current_users=$(psql  -U postgres  -c " SELECT * FROM pg_shadow;  " -d template1 | sed -e "1,2d" | cut -d"|" -f 1 | sed -e  'N;$!P;$!D;$d')
	/etc/init.d/postgresql start	
	while [ $# -ne 0 ]
	do	
		USER=$1
		present=$(echo $pgsql_current_users | grep $USER)
		if [ "X$present" == "X" ] ; then
			echo config_pgsql_base_user $USER
			config_pgsql_base_user $USER
		fi
		shift 1
	done
    yaimlog DEBUG "function config_pgsql_base_users stop"
}

config_pgsql_installed_test()
{
  yaimlog DEBUG "function config_pgsql_installed_test start"
  id postgres > /dev/null
  postgresidckrc=$?
  if [ "$postgresidckrc" != 0 ] ; then
    echo config_pgsql called but postgres users does not exist!
    echo Try creating user postgres and rerun Yaim 
    exit 1
  fi
  yaimlog DEBUG "function config_pgsql_installed_test stop"
}

config_pgsql_uninstall()
{
  yaimlog DEBUG "function config_pgsql_uninstall start"
  config_pgsql_installed_test
  /etc/init.d/postgresql stop
  yaim_query_conf_file_path_postgres_home
  pgdata=$RET
  if test -d ${pgdata}
  then
    rm -rf ${pgdata}
  fi
  yaimlog DEBUG "function config_pgsql_uninstall stop"
}

config_pgsql_install()
{
  yaimlog DEBUG "function config_pgsql_install start"
  config_pgsql_installed_test
  config_pgsql_base_init
  config_pgsql_base_access
  /etc/init.d/postgresql start
  yaimlog DEBUG "function config_pgsql_install stop"
}


config_sedcache_pgsql() 
{
# Check to see if postgres should be reinstalled
  yaimlog DEBUG "function config_sedcache_pgsql start"
  local rcdbserver
  local rcrmpgsql
  local rcdbserver
  
  yaim_query_conf_node_dcache_dbserver
  rcdbserver=$?
  if [ "$rcdbserver" == 1 ]
  then
    yaim_state_reset_postgresql
    rcrmpgsql=$?
    if [ "$rcrmpgsql" == 1 ]
    then
      yaim_query_conf_node_dcache_name_server
      rcnameserver=$?
      if [ "$rcrmpgsql" == 1 ] ; then
        yaim_state_nameserver_unmount
        yaim_state_nameserver_stop
      fi
      config_pgsql_uninstall
      RESET_DCACHE_PNFS=yes
      config_pgsql_install
    else
      yaim_state_postgresql_started
      postgresql_started=$?
      if [ "${postgresql_started}" != 0 ] ; then
        echo "Error: Postgresql is not started or producing an Error. Please set the variable"
        echo "Error: RESET_DCACHE_RDBMS=yes"
        echo "Error: or start the postgres database before running YAIM"
        exit 1
      fi
    fi
    config_pgsql_base_users "postgres" "pnfsserver" "srmdcache" "bill"
    check_postgresql_database_all
  fi
  yaimlog DEBUG "function config_sedcache_pgsql stop"
}
config_pgsql_check() 
{
  return 0
}
config_pgsql_run()
{
   config_sedcache_pgsql
}

config_pgsql()
{
  if [ "yes" == "$DESYOVERRIDE" ] ; then
    return 0
  fi
}
