#! /bin/bash
# -*- coding: utf-8 -*-
#
# Purge backupped postgres DB
#
# This free software is released under GNU Affero GPL3
# author: Antonio M. Vigliotti - antoniomaria.vigliotti@gmail.com
# (C) 2015-2019 by SHS-AV s.r.l. - http://www.shs-av.com - info@shs-av.com
#
READLINK=$(which greadlink 2>/dev/null) || READLINK=$(which readlink 2>/dev/null)
export READLINK
# Based on template 2.0.0
THIS=$(basename "$0")
TDIR=$(readlink -f $(dirname $0))
[ $BASH_VERSINFO -lt 4 ] && echo "This script $0 requires bash 4.0+!" && exit 4
if [[ -z $HOME_DEVEL || ! -d $HOME_DEVEL ]]; then
  [[ -d $HOME/odoo/devel ]] && HOME_DEVEL="$HOME/odoo/devel" || HOME_DEVEL="$HOME/devel"
fi
[[ -x $TDIR/../bin/python3 ]] && PYTHON=$(readlink -f $TDIR/../bin/python3) || [[ -x $TDIR/python3 ]] && PYTHON="$TDIR/python3" || PYTHON=$(which python3 2>/dev/null) || PYTHON="python"
[[ -z $PYPATH ]] && PYPATH=$(echo -e "import os,sys\no=os.path\na=o.abspath\nj=o.join\nd=o.dirname\nb=o.basename\nf=o.isfile\np=o.isdir\nC=a('"$TDIR"')\nD='"$HOME_DEVEL"'\nif not p(D) and '/devel/' in C:\n D=C\n while b(D)!='devel':  D=d(D)\nN='venv_tools'\nU='setup.py'\nO='tools'\nH=o.expanduser('~')\nT=j(d(D),O)\nR=j(d(D),'pypi') if b(D)==N else j(D,'pypi')\nW=D if b(D)==N else j(D,'venv')\nS='site-packages'\nX='scripts'\ndef pt(P):\n P=a(P)\n if b(P) in (X,'tests','travis','_travis'):\n  P=d(P)\n if b(P)==b(d(P)) and f(j(P,'..',U)):\n  P=d(d(P))\n elif b(d(C))==O and f(j(P,U)):\n  P=d(P)\n return P\ndef ik(P):\n return P.startswith((H,D,K,W)) and p(P) and p(j(P,X)) and f(j(P,'__init__.py')) and f(j(P,'__main__.py'))\ndef ak(L,P):\n if P not in L:\n  L.append(P)\nL=[C]\nK=pt(C)\nfor B in ('z0lib','zerobug','odoo_score','clodoo','travis_emulator'):\n for P in [C]+sys.path+os.environ['PATH'].split(':')+[W,R,T]:\n  P=pt(P)\n  if B==b(P) and ik(P):\n   ak(L,P)\n   break\n  elif ik(j(P,B,B)):\n   ak(L,j(P,B,B))\n   break\n  elif ik(j(P,B)):\n   ak(L,j(P,B))\n   break\n  elif ik(j(P,S,B)):\n   ak(L,j(P,S,B))\n   break\nak(L,os.getcwd())\nprint(' '.join(L))\n"|$PYTHON)
[[ $TRAVIS_DEBUG_MODE -ge 8 ]] && echo "PYPATH=$PYPATH"
for d in $PYPATH /etc; do
  if [[ -e $d/z0librc ]]; then
    . $d/z0librc
    Z0LIBDIR=$(readlink -e $d)
    break
  fi
done
[[ -z "$Z0LIBDIR" ]] && echo "Library file z0librc not found in <$PYPATH>!" && exit 72
[[ $TRAVIS_DEBUG_MODE -ge 8 ]] && echo "Z0LIBDIR=$Z0LIBDIR"
ZARLIB=$(findpkg zarrc "$PYPATH")
[[ -z "$ZARLIB" ]] && echo "Library file zarrc not found!" && exit 72
. $ZARLIB
[[ $TRAVIS_DEBUG_MODE -ge 8 ]] && echo "ZARLIB=$ZARLIB"
TESTDIR=$(findpkg "" "$TDIR . .." "tests")
[[ $TRAVIS_DEBUG_MODE -ge 8 ]] && echo "TESTDIR=$TESTDIR"
RUNDIR=$(readlink -e $TESTDIR/..)
[[ $TRAVIS_DEBUG_MODE -ge 8 ]] && echo "RUNDIR=$RUNDIR"

# DIST_CONF=$(findpkg ".z0tools.conf" "$PYPATH")
# TCONF="$HOME/.z0tools.conf"
CFG_init "ALL"
link_cfg_def
link_cfg $DIST_CONF $TCONF
[[ $TRAVIS_DEBUG_MODE -ge 8 ]] && echo "DIST_CONF=$DIST_CONF" && echo "TCONF=$TCONF"
get_pypi_param ALL
RED="\e[1;31m"
GREEN="\e[1;32m"
CLR="\e[0m"

__version__=2.0.4


OPTOPTS=(h        c        e      i      I       K        k          l       m          n            T         U          V           v)
OPTDEST=(opt_help opt_conf opt_ex opt_in opt_nce opt_cron opt_keep   opt_log opt_km     opt_dry_run  test_mode opt_user   opt_version opt_verbose)
OPTACTI=("+"      "="      1      1      1       1        "="        "="     "="        "1"          1         "="        "*>"        1)
OPTDEFL=(0        ""       0      0      0       0        ""         ""      ""         0            0         "postgres" ""          0)
OPTMETA=("help"   "file"   ""     ""     ""      "cron"   "# copies" "file"  "# copies" "do nothing" "test"    "username" "version"   "verbose")
OPTHELP=("this help"\
 "configuration file (def zar.conf)"\
 "exact DB name (rather matches DB name)"\
 "run inside backup (do not compress)"\
 "do not expand neither compress files"\
 "run in cron environment"\
 "keep # recent copies of db (max 60)"\
 "log filename (def /var/log/bckdb.log)"\
 "keep # of monthly copies of db (max 12)"\
 "do nothing (dry-run)"\
 "test mode (implies dry-run)"\
 "username (def postgres)"\
 "show version"\
 "verbose mode")
OPTARGS=(dbsel)

parseoptargs "$@"

if [ "$opt_version" ]
then
  echo "$__version__"
  exit 0
fi
if [ $opt_help -gt 0 ]
then
  print_help "Purge postgres DB"\
  "(C) 2015-2023 by zeroincombenze®\nhttp://wiki.zeroincombenze.org/en/Linux/dev\nAuthor: antoniomaria.vigliotti@gmail.com"
  exit 0
fi
CFG_init
conf_default "purgedb"
if [ $opt_cron -gt 0 ]; then
  detached_login "$@"
fi
link_cfg $FCONF
wlog "=== Starting purge backup $__version__ by $opt_user ==="

init_vars "$dbsel"
dblist=$(create_db_list_from_file "$DBSEL" "$PGDIR" "$DBCKDIR" "$REDB")
if [ "$BCKFORMAT" == "0" ]; then
  wlog "-- Backup keeps sql files --"
else
  wlog "-- Backupped DBs stored in compress tar files --"
fi
if [ "$BCK_ENV" == "PRD" ]; then
  wlog "-- Production environment --"
elif [ "$BCK_ENV" == "DEV" ]; then
  wlog "-- Development/backup environment --"
else
  wlog "-- Unique environment w/o dev/backup host --"
fi
wlog "PRD=$HOST_PRD//$URL_PRD"
wlog "DEV=$HOST_DEV//$URL_DEV"
wlog "- Files of DB to Purge:$dblist"
dovalid=0
for sfx in A B C D E F G H; do
  x=DB${sfx}
  XDB=${!x}
  x=NC${sfx}
  XNC=${!x}
  x=NA${sfx}
  XNA=${!x}
  [ -n "$XDB" ] && wlog "Keep $XNC recent copies copies and $XNA monthly copies of $XDB"
  [ -n "$XDB" ] && dovalid=1
done
ctr=0
pushd $DBCKDIR >/dev/null
if [ $dovalid -gt 0 ]; then
  for db in $dblist; do
    set_db_vars "$db"
    range=$XNC
    if [ -n "$range" ]; then
      mindate_r=$(date -d "today - $XNC day" +%Y%m%d)
      mindate_a=$(date -d "today - $XNA month" +%Y%m%d)
      [ $opt_nce -ne 0 ] || expand_tar $db
      wlog "Delete recent file older than $mindate_r (-$XNC days)"
      wlog "Delete monthly file older than $mindate_a (-$XNA months)"
      for fn in $db-*.sql; do
        dtc=${fn: -12: -4}
        if [[ ! $dtc =~ ^[0-9]+$ ]]; then
          dtc=99991231
        fi
        dd=${dtc: -2}
        if [ $dd -ne 1 -a $dtc -lt $mindate_r ] || [ $dd -eq 1 -a $dtc -lt $mindate_a ]; then
          if [ $opt_dry_run -gt 0 -a ${test_mode:-0} -eq 0 ]; then
            echo "File $fn should be deleted!"
          else
            wlog "File $fn deleted!"
            rm -f $fn
          fi
          ((ctr++))
        fi
      done
      dtc=$(date +%Y%m%d)
      [ $opt_in -ne 0 -o $opt_nce -ne 0 ] || compress_tar $db "$db-$dtc.sql"
    fi
  done
fi
popd >/dev/null
if [ $opt_dry_run -eq 0 ]; then
  wlog "== $ctr files are purged!"
else
  wlog "== $ctr files should be purged!"
fi
exit 0

