#!/usr/bin/env bash

set -o errexit
set -o nounset
set -o pipefail
# set -o xtrace

printf "\n## Start to archive PB of last month ... \n"
printf "\n## Current date is %s \n" "$(date)"
lastmonth=$(date -d "1 month ago" +%Y%m)
rootpath="/data/drainer/drainer.data"
archivepath=$rootpath$'/drainer.pb.'$lastmonth
archivedfile=$'drainer.pb.'$lastmonth.tgz

#. /home/tidb/.bash_profile
#. /home/tidb/.bashrc


function err_exit() {
  echo "ERROR: $1" 1>&2
  exit 1
}

function pre_checks() {
  which printf >/dev/null 2>&1 || err_exit "printf not found"
  which tar >/dev/null 2>&1 || err_exit "tar not found"
  which pigz >/dev/null 2>&1 || err_exit "pigz not found"
}

pre_checks

# prepare environment
mkdir -p $archivepath
mv $rootpath/binlog*-$lastmonth* $archivepath
printf "\n## Archive PB of last month is done. Now start to compress the archive path, the compression takes ... \n"

cd $rootpath
time tar -cf - $'drainer.pb.'$lastmonth --remove-files |pigz -p 64 > $archivedfile
printf "\n## Archive Finished! \n"