#!/bin/bash

#   BAREOS® - Backup Archiving REcovery Open Sourced
#
#   Copyright (C) 2017-2026 Bareos GmbH & Co. KG
#
#   This program is Free Software; you can redistribute it and/or
#   modify it under the terms of version three of the GNU Affero General Public
#   License as published by the Free Software Foundation and included
#   in the file LICENSE.
#
#   This program is distributed in the hope that it will be useful, but
#   WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
#   Affero General Public License for more details.
#
#   You should have received a copy of the GNU Affero General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
#   02110-1301, USA.

DATABASES="postgresql"
QUERY_NAMES_FILE="../bdb_query_names.inc"
QUERY_ENUM_FILE="../bdb_query_enum_class.h"

#DATE=`date '+%F %T'`

print_note()
{
  printf "/* autogenerated file by %s */\n" "$0"
  # the colon is injected, so this file doesn't contain the disable-string
  printf "/* bareos-check-sources%sdisable-copyright-check */\n\n" ":"
}

upper()
{
  tr "a-z" "A-Z" <<<"$1"
}

get_query_include_filename()
{
  printf "../%s_queries.inc" "$1"
}

#
# file header
#
: >$QUERY_NAMES_FILE
print_note >>$QUERY_NAMES_FILE
printf "const char *BareosDb::query_names[] = {\n" >>$QUERY_NAMES_FILE

: >$QUERY_ENUM_FILE
print_note >>$QUERY_ENUM_FILE
cat >>$QUERY_ENUM_FILE <<EOF
#ifndef BAREOS_CATS_BDB_QUERY_ENUM_CLASS_H_
#define BAREOS_CATS_BDB_QUERY_ENUM_CLASS_H_

class BareosDbQueryEnum {
 public:
  enum class SQL_QUERY
  {
EOF

for db in $DATABASES; do
  DB=${db^}
  queryincludefile=$(get_query_include_filename "${db}")
  : >"${queryincludefile}"
  print_note >>"${queryincludefile}"
done

#
# file data
#
((i = 0))
for query in $(ls ????_* | sed 's#\..*##g' | sort | uniq); do
  queryname=$(sed 's/[0-9]*_//' <<<"${query}")
  printf '"%s",\n' "$queryname" >>"${QUERY_NAMES_FILE}"
  printf "    %s = %s,\n" "$queryname" "$i" >>"${QUERY_ENUM_FILE}"

  if ((i != 0)); then
    # split queries by a single empty line, to make it easier to
    # visually seperate them
    echo "" >>"${queryincludefile}"
  fi

  ((i++))

  for db in $DATABASES; do
    queryincludefile=$(get_query_include_filename $db)
    queryfile="$query"
    if [ -e "$query.$db" ]; then
      queryfile="$query.$db"
    fi
    {
      printf '/* %s */\nR"SQL(' "${queryfile}"
      # remove comments and empty lines
      sed -r -e "/^#/d" -e "/^$/d" <"${queryfile}"
      printf ')SQL",\n'
    } >>"${queryincludefile}"
  done
done

#
# file footer
#

printf "NULL\n};\n" >>"${QUERY_NAMES_FILE}"

cat >>$QUERY_ENUM_FILE <<EOF
    SQL_QUERY_NUMBER = $i
  };
};

#endif  // BAREOS_CATS_BDB_QUERY_ENUM_CLASS_H_
EOF
