#! /bin/sh
#	@(#) pgsql.sh
#
#	(C) Copyright 2003 The SCO Group, Inc. All rights reserved.
#
PATH=/etc:/bin:/usr/bin:/usr/pgsql/bin:/usr/gnu/bin
LANG=C_C.C
export PATH LANG

ETCPGSQL=/etc/pgsql

# Define return values
: ${OK=0} ${FAIL=1} ${STOP=10} ${HALT=11}

# Set change to NO
change=NO
tmp=/tmp/pgsql.$$

ENABLED=
RUNNING=

# Define traps for critical and non critical code.
set_trap()  {	
	trap 'echo "Interrupted! Exiting ..."; cleanup 1' 1 2 3 15
}
unset_trap()  {
	trap '' 1 2 3 15
}
 
# Remove temp files and exit with the status passed as argument
cleanup() {
	trap '' 1 2 3 15
	[ "$tmp" ] && rm -f $tmp*
	exit $1
}

# clear the screen if it is supported
clearscr() {
	# check if the terminal environment is set up
	[ "$TERM" ] && [ -x /bin/clear ] && clear 2> /dev/null
}

# Prompt for yes or no answer - returns non-zero for no
getyn() {
	while	echo "\n$* (y/n) \c">&2
	do	read yn rest
		case $yn in
		[yY])	return $OK 			;;
		[nN])	return $FAIL			;;
		*)	echo "Please answer y or n" >&2	;;
		esac
	done
}

# Prompt with mesg, return non-zero on q
prompt() {
	while	echo "\n${mesg}or enter q to ${quit}: \c" >&2
	do	read cmd
		case $cmd in
		+x|-x)	set $cmd					;;
		Q|q)	return $FAIL					;;
		!*)	eval `expr "$cmd" : "!\(.*\)"`			;;
		"")	# If there is an argument use it as the default
			# else loop until 'cmd' is set
			[ "$1" ] && { 
				cmd=$1
				return $OK
			}
			: continue
			;;
		*)	return $OK					;;
		esac
	done
}

# Print an error message
error() {
	echo "\nError: $*" >&2
	return $FAIL
}

#
# get_status - Get the current start/stop/running status
get_status() {
  cstat=`MKDEV_INVOKED=true $ETCPGSQL status`
  if test -z "$cstat" -o $? -ne 0; then
    error "/etc/pgsql execution failed"
    exit $FAIL
  else
    set -- $cstat
    if test "$1" = "R"; then
      RUNNING=""
    else
      RUNNING=" not"
    fi
    ENABLED=$2
  fi
}

#
# owner_pgsql - Set the database owner
######################################
owner_pgsql() {
  if test -z "$RUNNING"; then
    error "\nYou must stop PostgreSQL before changing the database owner"
    return $FAIL
  fi

  olduser=$PGSQLUSER
  echo "\nYou are about to change the PostgreSQL database owner. SCO recommends
that you leave this as the unprivileged user 'nouser' for improved security.
This user has no login shell, so when you need to run database administration 
commands such as createdb as this user you should use the -s option to 'su' to
specify a shell to use. For example, to use the Bourne shell, use the command:

   su -s /bin/sh nouser

If you decide to create a different user, it will be given the default shell,
which is the Bourne shell. You should consider changing this to /bin/false and
using 'su -s /bin/sh' to start an interactive shell as that user.\n"

  while 
  mesg="The current database owner is: $PGSQLUSER
Enter the new database owner "
  quit="to leave unchanged"
  do prompt || break
    if test -n "$cmd"; then
      if test "$cmd" != "$PGSQLUSER"; then
	PGSQLUSER=$cmd
	change=YES
      fi
      break;
    fi
  done

  firstch=`echo $PGSQLUSER|sed -e 's/\\(.\\).*/\\1/'`
  tcbf="/tcb/files/auth/$firstch/$PGSQLUSER"

  if test ! -f $tcbf; then
    echo "\nThe user '$PGSQLUSER' does not exist. If you allow this script
to create the user for you, it will create a pseudo user owned
by itself. If you want the user to be a general purpose user account
you will need to change the account using scoadmin."
    getyn "Create user '$PGSQLUSER'?"
    if test $? -eq $OK; then
      while mesg="Enter user ID to assign to user $PGSQLUSER "
	quit="quit"
      do prompt || break
	bad=0
	awk -F : -e '{print $3}' /etc/passwd | grep "^$cmd\$" > /dev/null 2>&1
	if test $? -eq 0; then
	  echo "That user ID already exists!"
	  bad=1
	fi
	x=`expr $cmd \\* 1 2> /dev/null`
	if test -z "$x"; then x=0; fi
	if test "$x" != "$cmd" -o $? -ne 0 -o $x -lt 11 -o $x -gt 64999; then
	  echo "The user ID must be numeric and in the range 11 though 64999"
	  bad=1
	fi
	if test $bad -eq 0; then
	  PGUSERID=$cmd
	  break;
        fi
      done
      if test $? -ne $OK; then
	return $FAIL
      fi

      if test -e /tcb/files/auth/r/root; then
        sed -e "s/@USERID@/$PGUSERID/g" -e "s/@USERNAME@/$PGSQLUSER/g" > $tcbf <<EOF
@USERNAME@:u_name=@USERNAME@:u_id#@USERID@:\\
	:u_pwd=*:\\
	:u_type=pseudo:u_owner=@USERNAME@:u_cmdpriv=:\\
	:u_syspriv=nopromain:\\
	:u_pswduser=@USERNAME@:u_lock@:chkent:
EOF
	chown root $tcbf
	chgrp auth $tcbf
	chmod 0660 $tcbf
      fi
      echo "$PGSQLUSER:x:$PGUSERID:28:PostgreSQL database owner:/:" >> /etc/passwd
      if test -e /etc/shadow; then
        echo "$PGSQLUSER:*:::" >> /etc/shadow
      fi
    fi
  fi

  if [ ! -f /var/adm/postgres ]; then
    echo "PostgreSQL log file" > /var/adm/postgres
  fi
  chown $PGSQLUSER /var/adm/postgres

  echo "\n\nThe PostgreSQL log file and database files must all be owned by"
  echo "this user ($PGSQLUSER). If you answer yes to the question below"
  echo "all files in the data directory will be changed to be owned by $PGSQLUSER."
  echo "If you plan on changing the database directory as well, you may wish"
  echo "to leave the current ownership intact."
  getyn "Change ownership in '$PGSQLDATA'?"
  if test $? -eq $OK; then
    chown -R $PGSQLUSER $PGSQLDATA
  fi
  return $OK
}

#
# database_pgsql - Change the database location
###############################################
database_pgsql() {
  if test -z "$RUNNING"; then
    error "\nYou must stop PostgreSQL before changing the database location"
    return $FAIL
  fi

  while 
  mesg="The current database location is: $PGSQLDATA
Enter the new database location "
  quit="to leave unchanged"
  do prompt || break
    if test -n "$cmd"; then
      if test "$cmd" != "$PGSQLDATA"; then
	PGSQLDATA=$cmd
	change=YES
	break;
      fi
    fi
  done

  return $OK
}

#
# cfg_pgsql - Configure various parameters
##########################################
cfg_pgsql() {
  anywork=n
  PLSENABLE=
  clearscr
  while mesg="\n\nPostgreSQL Configuration Menu\n
	1.  Enable PostgreSQL
	2.  Disable PostgreSQL
	3.  Start PostgreSQL postmaster process
	4.  Stop PostgreSQL postmaster process
	    (after all clients have disconnected)
	5.  Stop PostgreSQL postmaster process NOW
	6.  Restart PostgreSQL postmaster process
	    (after all clients have disconnected)
	7.  Restart PostgreSQL postmaster process NOW
	8.  Set PostgreSQL database owner
	9.  Set PostgreSQL database directory

	Select an option "
	quit="return to the main menu"
  do prompt || break
    anywork=y
    select=$cmd
    case $select in
      1) PLSENABLE=E; echo "\nPostgreSQL will be enabled"	;;
      2) PLSENABLE=D; echo "\nPostgreSQL will be disabled"	;;
      3) $ETCPGSQL start; get_status	;;
      4) $ETCPGSQL stop; get_status	;;
      5) $ETCPGSQL stop -m fast; get_status	;;
      6) $ETCPGSQL restart; get_status	;;
      7) $ETCPGSQL restart -m fast; get_status	;;
      8) owner_pgsql		;;
      9) database_pgsql		;;
      *) echo "\n\tPlease select either 1, 2, 3, 4, 5, 6, or 7"
         continue		;;
    esac

    get_status

    if test ! -f /var/adm/postgres; then
      echo "PostgreSQL log file" > /var/adm/postgres
    fi
    chown $PGSQLUSER /var/adm/postgres

    if test ! -d $PGSQLDATA; then
      echo "\nThe directory $PGSQLDATA does not exist."
      getyn "Create directory '$PGSQLDATA'?"
      if test $? -eq $OK; then
        mkdir -p $PGSQLDATA
        chown $PGSQLUSER $PGSQLDATA
        chgrp nogroup $PGSQLDATA
        chmod 700 $PGSQLDATA
      fi
    fi

    if test -d $PGSQLDATA -a ! -f $PGSQLDATA/PG_VERSION; then
      echo "\nThe directory $PGSQLDATA does not contain a
valid database, and the directory should be initialized."
      getyn "Initialize databases in $PGSQLDATA?"
      if test $? -eq $OK; then
        LANG=C /bin/su -S -s /bin/sh $PGSQLUSER -c "/usr/bin/initdb -D $PGSQLDATA"
      fi
    fi

    if test "$change" = "YES"; then
      if test -f /etc/default/pgsql; then
        sed -n -e '/^#/p' /etc/default/pgsql > ${tmp}dflt
      fi
      echo "PGSQLUSER=$PGSQLUSER" >> ${tmp}dflt
      echo "PGSQLDATA=$PGSQLDATA" >> ${tmp}dflt
      cp -f ${tmp}dflt /etc/default/pgsql
      rm -f ${tmp}dflt
      change=NO
    fi
  done

  if test -n "$PLSENABLE" -a "$PLSENABLE" != "$ENABLED"; then
    if test "$PLSENABLE" = "E"; then
      $ETCPGSQL enable
    else
      $ETCPGSQL disable
    fi
    get_status
  fi

  return $OK
}

#
# show_pgsql - Show the current configuration parameters and status
###################################################################
show_pgsql() {
  get_status
  echo "
Current PostgreSQL configuration and status:
"
  if test "$ENABLED" = "E"; then
    ISENABLED=""
  else
    ISENABLED=" not"
  fi

  echo "\tPostgreSQL is$RUNNING currently running"
  echo "\tPostgreSQL is$ISENABLED currently enabled"
  echo "\tThe postmaster process will run as user '$PGSQLUSER'"
  echo "\tThe database located in the directory $PGSQLDATA"
}

# main()
#########################

if [ `id -u ` != 0 ];  then 
	echo "You have to be superuser to run $0 ..."
	exit 1
fi

PGSQLDIR=/usr/pgsql

if test -e /etc/default/pgsql; then
	. /etc/default/pgsql
fi

#
# If special parameters were not set, set the defaults
#
if test -z "$PGSQLUSER"; then
  if test -e /tcb/files/auth/p/postgres; then
    PGSQLUSER=postgres
  else
    PGSQLUSER=nouser
  fi
fi

if [ ! -f /var/adm/postgres ]; then
  echo "PostgreSQL log file" > /var/adm/postgres
fi
chown $PGSQLUSER /var/adm/postgres

if test -z "$PGSQLDATA"; then
  PGSQLDATA="$PGSQLDIR/data"
fi

set_trap

umask 022
cd /
clearscr
while mesg="\n\nPostgreSQL Configuration Program\n
	1. Configure PostgreSQL
	2. View current PostgreSQL configuration

	Select an option "
	quit="quit"
do prompt || break
	# reset these flags prior to each pass through menu
	get_status
	select=$cmd
	case $select in
	1)	cfg_pgsql	;;
	2)	show_pgsql	;;
	*)	echo "\n	Please select either 1 or 2"
		continue	;;
	esac
done

cleanup $OK
