#!/bin/sh

APP_NAME=$1

APP_DB=`echo $APP_NAME | sed 's/_report//'`
APP_DB_TABLES="/usr/clearos/apps/$1/deploy/db_tables.sql"

if [ "$2" == "yes" ]; then
    FORCE="yes"
else
    FORCE=""
fi

MYSQL="/usr/clearos/sandbox/usr/bin/mysql"
DB_CONFIG="/var/clearos/system_database/root"

# Start system database
#----------------------

/usr/clearos/apps/reports_database/deploy/initialize-database

# Grab root database password
#----------------------------

ROOTPASS=`grep ^password $DB_CONFIG 2>/dev/null | sed "s/^password[[:space:]]*=[[:space:]]*//"`

if [ -z "$ROOTPASS" ]; then
    echo "Unable to authenticate with database"
    exit 1
fi

# Create tables (if necessary)
#-----------------------------

TABLE_EXISTS=`$MYSQL -uroot -p"$ROOTPASS" -e 'show tables;' reports 2>/dev/null | grep ^$APP_DB$`

if ( [ -z "$TABLE_EXISTS" ] || [ -n "$FORCE" ] ); then
    echo "creating tables for $APP_NAME"
    logger -p local6.notice -t installer "app-reports-database-core - creating tables for $APP_NAME"
    $MYSQL -uroot -p"$ROOTPASS" reports < $APP_DB_TABLES
else
    echo "tables already exist for $APP_NAME"
fi
