#!/bin/bash -f
#
# Calculate memory parameters for PostgreSQL-7.1 on Linux.
#
#    This program calculate sample values of "sort_mem" and "shared_buffers"
#  in $PGDATA/postgresql.conf for your Linux environment according to your
#  Linux configurated parameters.
#
# Author: Jun Kuwamura
# Creation: 2001-04-11
#
  bug_report_to="juk@yokohama.email.ne.jp"
#
CMDNAME=`basename $0`

# set default and parameter
##max_connections = 32 # 1-1024
max_connections=32
denominator=2

help="\
$CMDNAME: Calculate memory parameters for PostgreSQL-7.1

Usage:
    $CMDNAME [-n max_connections]
	where;
	    max_connections: number of maximum connections
				[default $max_connections]

Report bugs to <$bug_report_to>." 
advice="\
Try '$CMDNAME --help' for more information."


while [ "$#" -gt 0 ]
do
    case $1 in
        -h|--help|-\?)
            echo "$help"
            exit 0
            ;;
        -n|--max_connections)
            max_connections=$2
            shift
            ;;
        *)
            echo "$CMDNAME: invalid option or parameter: $1" 1>&2
            echo "$advice" 1>&2
            exit 1
            ;;
    esac
    shift
done

if [ $max_connections -lt 1 -o $max_connections -gt 1024 ]; then
	echo "max_connections must be between 1 and 1024"
	exit
fi

##sort_mem = 512	# [k bytes]
#sort_mem = 1024	# core_mem / 10 / max_connections
#
core_mem=`free | grep Mem: | awk '{print $2}'`
sort_mem=`expr $core_mem / $denominator / $max_connections`


##shared_buffers = 2*max_connections # min 16 [8k bytes]
#shared_buffers = 2048	# [8k bytes]
#
#shm_max_hex=`fgrep SHMMAX /usr/include/asm/shmparam.h | grep "^#define" | awk '{print $3}'`
#shm_max_bytes=`printf "%d" $shm_max_hex`
shm_max_bytes=`cat /proc/sys/kernel/shmmax`
shm_max=`expr $shm_max_bytes / 1024`
shared_buffers=`expr $shm_max / $denominator / 8`

# check minimum number of buffers
shared_buffers_min=`expr $max_connections \* 2`
if [ $shared_buffers -lt $shared_buffers_min ]; then
	shared_buffers=$shared_buffers_min
fi

echo "max_connections = $max_connections"
echo "sort_mem = $sort_mem"
echo "shared_buffers = $shared_buffers"
