#! /bin/sh

if [ -f "/etc/debian_version" ]; then
 ECHO="echo"
else
 ECHO="echo -e"
fi

substline()
{
  temp=$$
  x=`grep -n "$1" $3 | cut -d: -f1`
  x=$(($x-1))
  sed -n '1,'$x'p' $3 >$temp
  $ECHO $2 >>$temp
  x=$(($x+1))
  x=$(($x+1))
  sed -n ''$x',$p' $3 >>$temp
  cp -f $temp $3
  rm -rf $temp
}

cd /mnt/usb
pgsqltar="/mnt/usb/pgsql.tgz"
TAR="tar"
TAR_ARGS="zxvf"

if [ ! -d /mnt/usb/igateway ]; then
{
 echo "Vortiqa not installed...."
 echo -e "\033[31mAborted PGSQL Installation !!.\033[00m"
 exit
}
fi

$TAR $TAR_ARGS $pgsqltar >/dev/null

cp postgresql-8.3.4 /etc/rc.d/init.d/
chmod +x /etc/rc.d/init.d/postgresql-8.3.4

adduser -s /bin/sh -D pgadmin

mkdir /mnt/usb/pgsql/data
chown pgadmin /mnt/usb/pgsql/data
chmod 0777 /mnt/usb/tmp

#su pgadmin

su -c "/mnt/usb/pgsql/bin/initdb -D /mnt/usb/pgsql/data" pgadmin

#You can now start the database server using: 
#/mnt/usb/pgsql/bin/postgres -D /mnt/usb/pgsql/data

#)Open /mnt/usb/pg-data/pg_hba.conf
#Open /mnt/usb/pg-data/postgresql.conf

#exit the user 'pgadmin'
#exit

chown -R postgres /mnt/usb/pgsql/data
/etc/rc.d/init.d/postgresql-8.3.4 start

#su pgadmin

#the following step dpends on 'libpq.so' and hence igateway need to be installed before this.
if [ ! -f /usr/lib/libpq.so.5 ]; then
{
ln -s /igateway/lib/libpq.so /usr/lib/libpq.so.5 ;
}
fi
echo -e "\033[32mCreating new role "freescale" for VortiQa log database\033[00m"
echo "NOTE: VortiQa uses "freescale" as default role and "fsl123" as default password"
echo " If different password is used, VortiQa configuration should be changed accordingly."

su -c "/mnt/usb/pgsql/bin/createuser -s -P freescale" pgadmin
#Above step will prompt you for a password, enter it as 'fsl123',
#then it prompts for confirmation, confirm it as 'fsl123'

#exit
#exit the user 'pgadmin'

/etc/rc.d/init.d/postgresql-8.3.4 stop

## All the above is only one-time procedure ##
## You can now start iGateway (sh /igateway/igw_startup.sh) ##
  hbaconf="/mnt/usb/pgsql/data/pg_hba.conf"
        
entry=
entry1=
hostfld="host    all         all         0.0.0.0/0   trust"
entry=`egrep "host [[:space:]]*all [[:space:]]*all [[:space:]]*127.0.0.1" $hbaconf`
        
if [ -n "$entry" ]; then
  substline "$entry" "$hostfld" $hbaconf
fi
          
entry1=`egrep "host [[:space:]]*all [[:space:]]*all [[:space:]]*0.0.0.0" $hbaconf`
if [ -n "$entry1" ]; then
  $ECHO ""
else
  $ECHO "$hostfld" >>$hbaconf
fi
              
  pgconf="/mnt/usb/pgsql/data/postgresql.conf"

  address=`grep listen_addresses $pgconf`
if [ -n "$address" ]; then
  substline "listen_addresses" "listen_addresses = '*'" $pgconf
fi
                      
