#!/bin/bash
#pre: pg started as postgresql-14.service
#as root
echo "begin recovery, in any dir"
while [ $# -gt 0 ]; do
  COMMAND=$1
  case $COMMAND in    
    -time)
      time=$2
      shift 2
      ;;
    -tl)
      tl=$2
      shift 2
      ;;
    -backup)
      backup=$2
      shift 2
      ;;
    -data)
      data=$2
      shift 2
      ;;
    *)
      break
      ;;
  esac
done
echo "target time $time timeline $tl using backup dir $backup datadir $data"
echo "stop pg"
systemctl stop postgresql-14.service

#su - postgres
echo "backup current db"
#dataCurBak="$data_bak"
#echo $dataCurBak
mv $data ${data}_bak
#echo "del cur data"
#rm -rf $data
echo "restore backup"
cp -rf $backup $data
echo "set recovery target time"
touch $data/recovery.signal
sed -i "s/^recovery_target_time =.*/recovery_target_time = '$time'/g" $data/postgresql.conf
sed -i "s/^recovery_target_timeline =.*/recovery_target_timeline = '$tl'/g" $data/postgresql.conf
chown -R postgres $data

echo "start pg"
systemctl start postgresql-14.service