/**
 * Initialize a mysqli connector using the credentials stored in SECRETS_FILE
 *
 * @uses initSecrets() If $secrets is not already initialized
 *
 * @return mysqli A valid mysqli connector to the database backing the CanvasAPIviaLTI instance
 *
 * @throws CanvasAPIviaLTI_Exception MYSQL_CONNECTION if a mysqli connection cannot be established
 **/
function initMySql()
{
    global $secrets;
    // FIXME grown-ups don't program like this
    if (!$secrets instanceof SimpleXMLElement) {
        $secrets = initSecrets();
    }
    /* turn off warnings, since we're going to test the connection ourselves */
    set_error_handler(function () {
    });
    $sql = new mysqli((string) $secrets->mysql->host, (string) $secrets->mysql->username, (string) $secrets->mysql->password, (string) $secrets->mysql->database);
    restore_error_handler();
    if ($sql->connect_error) {
        throw new CanvasAPIviaLTI_Exception($sql->connect_error, CanvasAPIviaLTI_Exception::MYSQL_CONNECTION);
    }
    return $sql;
}
/* test if we already have a working install... */
if ($ready && !isset($_REQUEST['step'])) {
    $smarty->addMessage('App already installed', 'It appears that the application has already been installed and is ready for
		 use.');
    /* ...otherwise, let's start with the SECRETS_FILE */
} else {
    if (!file_exists(SECRETS_FILE)) {
        if (isset($_REQUEST['step']) && $_REQUEST['step'] == CanvasAPIviaLTI_Installer::SECRETS_ENTERED_STEP) {
            CanvasAPIviaLTI_Installer::createSecretsFile(CanvasAPIviaLTI_Installer::SECRETS_ENTERED_STEP);
        } else {
            CanvasAPIviaLTI_Installer::createSecretsFile();
        }
    }
}
/* establish our database connection */
$secrets = initSecrets();
$sql = initMySql();
try {
    if (!isset($_REQUEST['step'])) {
        /* load all of our various schema into the database... */
        CanvasAPIviaLTI_Installer::createLTIDatabaseTables();
        CanvasAPIviaLTI_Installer::createAppDatabaseTables();
        /* ...and initialize the app metadata... */
        $metadata = CanvasAPIviaLTI_Installer::createAppMetadata();
        /* ...optionally, acquire an API token for the app */
        CanvasAPIviaLTI_Installer::acquireAPIToken(CanvasAPIviaLTI_Installer::API_DECISION_NEEDED_STEP);
    } else {
        $metadata = new AppMetadata($sql, $secrets->app->id);
        $skip = isset($_REQUEST['skip']) ? $_REQUEST['skip'] : false;
        CanvasAPIviaLTI_Installer::acquireAPIToken($_REQUEST['step'], $skip);
    }