#!/bin/bash

set -e

source /etc/docker/xivo/custom.env

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

    PGPASSWORD=${pgpass} psql -h "${dbhost}" -p "${dbport}" -d "${dbname}" -U "${dbusername}" -qAtc "DELETE FROM ${table} WHERE time < now() - interval '${daystokeep}'"
}

main() {
  local daystokeep="${1:-365}"
  echo 'Check USM database exists...'
  if ! check_db_usm_exists; then
    echo 'Database USM dont exists, cant purge data'
    exit 0
  else 
    echo 'Purging data...'
    purge_usm_table "${USM_EVENT_SECRET}" "localhost" "5432" "usm" "event" "evt.event_login" "${daystokeep} days"
    purge_usm_table "${USM_CONFIG_SECRET}" "localhost" "5432" "usm" "config" "cfg.config_xivo" "${daystokeep} days"
  fi
  echo 'Done; USM database has been purged'
}

main "${@}"