#!/bin/bash

DATABASE=`/sbin/e-smith/db configuration getprop bugzilla DbDatabase|| echo "bugzilla"`
USERNAME=`/sbin/e-smith/db configuration getprop bugzilla DbUser|| echo "bugzilla"`
PASSWORD=`/sbin/e-smith/db configuration getprop bugzilla DbPassword|| echo "bugzilla-changeme"`

# count if table in bugzilla db
res=`/usr/bin/mariadb --defaults-file=/root/.my.cnf $socket -e "select count(*) from information_schema.tables where table_type = 'BASE TABLE' and table_schema = '$DATABASE'" | tail -n1`;

/usr/bin/mariadb -e "CREATE DATABASE IF NOT EXISTS $DATABASE DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;"


# if no bugzilla db or empty
if [[ $res == '0' ]]; then
  if  [ -f /home/e-smith/db/mariadb105/$DATABASE.dump ]; then
     echo "Mariadb database empty and there was a backup in /home/e-smith/db/mariadb105/$DATABASE.dump; restoring it ..."
     /usr/bin/mariadb --defaults-file=/root/.my.cnf $socket $dbname < /home/e-smith/db/mariadb105/$DATABASE.dump && mv /home/e-smith/db/mariadb105/$DATABASE.dump /home/e-smith/files/nextcloud/data/mariadb105-$DATABASE.dump
  elif [ -f /home/e-smith/db/myslq/$DATABASE.dump ]; then
     echo "Mariadb database empty and there was a backup in /home/e-smith/db/myslq/$DATABASE.dump; restoring it ..."
     /usr/bin/mariadb --defaults-file=/root/.my.cnf $socket $dbname < /home/e-smith/db/mariadb105/$DATABASE.dump
  else
      echo "Fresh install detected ..."
  fi
fi

/usr/bin/mariadb -e "USE mysql; GRANT SELECT,INSERT,UPDATE,DELETE,INDEX,ALTER,CREATE,DROP,REFERENCES,LOCK TABLES,CREATE TEMPORARY TABLES ON $DATABASE.* TO $USERNAME@localhost IDENTIFIED BY '$PASSWORD'; FLUSH PRIVILEGES;" 

/etc/e-smith/events/actions/bugzilla
