#!/bin/bash

set -e

readonly progname="${0##*/}"

is_mds() {
  [ -f /var/lib/xivo/mds_enabled ]
}

check_db_usm_exists() {
  psql -U postgres -tc "SELECT 1 FROM pg_database WHERE datname = 'usm'" | grep -q 1
}

purge_usm_table() {
  local pgpass="${1:-proformatique}"; shift
  local dbhost="${1:-localhost}"; shift
  local dbport="${1:-5432}"; shift
  local dbname="${1: -usm}"; shift
  local dbusername="${1:-postgres}"; shift
  local table="${1}"; shift
  local daystokeep="${1}"; shift

  if res=$(PGPASSWORD=${pgpass} psql -h "${dbhost}" -p "${dbport}" -d "${dbname}" -U "${dbusername}" -qAtc "DELETE FROM ${table} WHERE time < now() - interval '${daystokeep}'" 2>&1); then
    echo "Purge of ${dbname}.${table} data older than ${daystokeep} with success."
  else
    echo "Error during purge of ${dbname}.${table} data older than ${daystokeep}: $res"
  fi
}

main() {
  local daystokeep="${1:-365}"

  # Do not execute this cron on MDS
  # There is no USM db
  if is_mds; then
    echo 'Exiting: USM db does not exist on MDS' | logger -t "${progname}"
    exit 0
  fi

  source /etc/docker/xivo/custom.env

  echo 'Check USM database exists...' | logger -t "${progname}"
  if ! check_db_usm_exists; then
    echo 'Exiting: Database USM does not exists, cant purge data' | logger -t "${progname}"
    exit 0
  else 
    echo 'Purging data...' | logger -t "${progname}"
    purge_usm_table "${USM_EVENT_SECRET}" "localhost" "5432" "usm" "event" "evt.event_login" "${daystokeep} days" | logger -t "${progname}"
    purge_usm_table "${USM_CONFIG_SECRET}" "localhost" "5432" "usm" "config" "cfg.config_xivo" "${daystokeep} days" | logger -t "${progname}"
  fi
  echo 'Done; USM database has been purged' | logger -t "${progname}"
}

main "${@}"