#!/bin/bash
[ "$1" == "" ] && exec echo "Usage: $0 <TABLE_NAME> <SEARCH STRING> <DBBACKUP DATE START> <DBBACKUP DATE END>"
source $HOME/.gamerc

TABLE_NAME=$1
SEARCH_STR=$2
DATE_START=$3
DATE_END=$4

cd $HOME/DBbackup

if [ "${DATE_END}" == "" ]; then
  DATE=${DATE_START}
  if [ "${DATE}" == "" ]; then
      DBBACKUP_FILENAME="${GAME_TYPE}DB*sql"
  else
      DBBACKUP_FILENAME="${GAME_TYPE}DB[0-9]*-${DATE}*sql"
  fi

  for file in $(find . -maxdepth 1 -name "${DBBACKUP_FILENAME}" ! -size "0" -printf "%T+ %p\n" | sort | awk -F" " '{print $2}'); do
    echo ${file}
    dbbackup_file_date=$(echo ${file}|awk -F"-" '{print $2}'|sed 's/\.custom//')
    echo ${dbbackup_file_date}
    pg_restore -t ${TABLE_NAME} ${file} -f - | grep "${SEARCH_STR}"
    echo
  done
else
  for DATE in $(seq ${DATE_START} ${DATE_END}); do
    DBBACKUP_FILENAME="${GAME_TYPE}DB[0-9]*-${DATE}*sql"

    for file in $(find . -maxdepth 1 -name "${DBBACKUP_FILENAME}" ! -size "0" -printf "%T+ %p\n" | sort | awk -F" " '{print $2}'); do
      echo ${file}
      dbbackup_file_date=$(echo ${file}|awk -F"-" '{print $2}'|sed 's/\.custom//')
      echo ${dbbackup_file_date}
      pg_restore -t ${TABLE_NAME} ${file} -f - | grep "${SEARCH_STR}"
      echo
    done
  done
fi
