#!/bin/bash -
#===============================================================================
#
#          FILE:  getacopy
#
#         USAGE:  ./getacopy <DB Name> [Table name] [Search string or "truncate"]
#
#   DESCRIPTION:  Dump a copy from PostgreSQL
#
#  REQUIREMENTS:  postgres
#        AUTHOR: rickz (Rick Zhang), xlrickz@gmail.com
#       COMPANY: X-LEGEND Entertainment Corp.
#       CREATED: Wed Jan 05 11:23:35 CST 2011
#      REVISION:  1.1
#===============================================================================

#set -o nounset                              # Treat unset variables as an error
#set -m                                      # Enable job control

[ "$1" == "" ] && exec echo "Usage: $0 <DB Name> [Table name] [Search string or \"truncate\"]

Search string could be:
20101211
or
20101211,206784

eg.
\$ $0 SpiritKingAccount worlds 1100
1100    world-ch1       111.111.111.35  5565    1       1000    1       003.130.61.61   0 
"

if [ "$3" == "" ] ;then
	if [ "$2" == "" ] ; then
		pg_dump -U postgres "$1"
	else
	        pg_dump -U postgres -t "$2" "$1" | sed -n "/COPY $2 /,/^$/p"
	fi
else
	if grep -qi truncate <<< "$3" ; then
		echo "TRUNCATE TABLE $2;"
		pg_dump -U postgres -t "$2" "$1" | sed -n "/COPY $2 /,/^$/p"
	else
	        SEARCHSTRING="$(sed 's/,/\[\[:blank:\]\]/g' <<< "$3")"
        	pg_dump -U postgres -t "$2" "$1" | grep -i "$SEARCHSTRING"
	fi

fi                                                                 

