#!/bin/bash
set -e

. "${rscripts}/functions"

print_debug "drop database \"${db_name}\""
"${scripts}/drop_bareos_database"   2>&1 > /dev/null ||\
  echo "info: ${scripts}/drop_bareos_database failed"

print_debug "creating database \"${db_name}\""
"${scripts}/create_bareos_database"  2>&1 > /dev/null

print_debug "making tables  \"${db_name}\""
"${scripts}/make_bareos_tables"  2>&1 > /dev/null

print_debug "granting privileges database \"${db_name}\""
"${scripts}/grant_bareos_privileges"  2>&1 > /dev/null ||\
  echo "info: ${scripts}/grant_bareos_privileges failed"

if lsof="$(command -v lsof)"; then
  for port in $BASEPORT $BAREOS_DIRECTOR_PORT $BAREOS_STORAGE_PORT \
    $BAREOS_STORAGE2_PORT $BAREOS_FD_PORT $MINIO_PORT; do
    if pid=$("${lsof}" -ti "tcp:$port"); then
      print_debug "Killing process listening on $port with PID $pid"
      kill -9 "$pid"
    fi
  done
fi
exit 0
