<?php
require_once(dirname(__FILE__) . '/includes/base.inc.php');

route_request();

function route_request()
{
    if (install_needed() == false) {
        header('Location: ' . get_base_url());
        exit();
    }

    $pageopt = get_pageopt();
    if ($pageopt == 'install')
        do_install();

    show_install();
}

// Show the install form to the user
function show_install()
{
    $title = _('Install');

    $internal_url = get_base_url();
    $admin_name = _('Nagios Administrator');
    $admin_email = 'root@localhost';
    $admin_password = random_string(18, '@$!%&*.,');
    
    // The default timezone needs to be set before being accessed -AC
    set_option('default_timezone', 'UTC');
    get_timezones_and_selected($timezones, $timezone);
    get_themes_and_selected($themes, $theme);
    
    print_parent_page_top($title, null, null, null, false);
?>
<script>
// frame buster
if (top.location != self.location) {
    top.location = self.location.href;
}
</script>
<?php echo get_flash_message(); ?>
<div style="margin: 20px 30px">
    <h1><?php echo $title; ?></h1>
    <p style="margin-bottom: 20px"><?php echo _("Welcome to the Nagios Fusion installation. Just answer a few simple questions and then you'll be all set!"); ?></p>
    <form method="post"  class="formbuilder" >
        <input name="install"  value="1"  type="hidden"  />
        <div class="formbuilder-div formbuilder" >
            <h5 class="ul" >
                <?php echo _('General Program Settings'); ?>
            </h5>
            <table class="formbuilder-table formbuilder" >
                <tr>
                    <td>
                        <label for="internal_url" >
                            <?php echo _('Internal URL'); ?>:
                        </label>
                    </td>
                    <td>
                        <input name="internal_url"  value="<?php echo $internal_url; ?>"  type="text"  id="internal_url"  class="form-control textfield" required="true" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <label>
                            <?php echo _('Administrator Username'); ?>
                        </label>
                    </td>
                    <td>
                        <input value="nagiosadmin"  disabled  type="text" class="form-control textfield"  />
                    </td>
                </tr>
                <tr>
                    <td>
                        <label for="admin_name" >
                            <?php echo _('Administrator Name'); ?>:
                        </label>
                    </td>
                    <td>
                        <input name="admin_name"  placeholder="<?php echo $admin_name; ?>"  value="<?php echo $admin_name; ?>"  type="text"  id="admin_name"  class="form-control textfield" required="true" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <label for="admin_email" >
                            <?php echo _('Administrator Email'); ?>:
                        </label>
                    </td>
                    <td>
                        <input name="admin_email"  placeholder="<?php echo $admin_email; ?>"  value="<?php echo $admin_email; ?>"  type="email"  id="admin_email"  class="form-control textfield" required="true" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <label for="admin_password" >
                            <?php echo _('Administrator Password'); ?>:
                        </label>
                    </td>
                    <td>
                        <input name="admin_password"  value="<?php echo $admin_password; ?>"  type="text"  id="admin_password"  class="form-control textfield" required="true" />
                    </td>
                </tr>
            </table>
        </div>
        <div class="formbuilder-div formbuilder" >
            <h5 class="ul" >
                <?php echo _('Timezone Settings'); ?>
            </h5>
            <table class="formbuilder-table formbuilder" >
                <tr>
                    <td>
                        <label for="timezone" >
                            <?php echo _('Timezone'); ?>:
                        </label>
                    </td>
                    <td>
                        <select name="timezone"  id="timezone"  class="dropdown form-control" >
                            <?php echo get_options_from_array($timezones, $timezone); ?>
                        </select>
                    </td>
                </tr>
            </table>
        </div>
        <div class="formbuilder-div formbuilder" >
            <h5 class="ul" >
                <?php echo _('Theme Settings'); ?>
            </h5>
            <table class="formbuilder-table formbuilder" >
                <tr>
                    <td>
                        <label for="theme" >
                            <?php echo _('Theme'); ?>:
                        </label>
                    </td>
                    <td>
                        <select name="theme"  id="theme"  class="dropdown form-control" >
                            <?php echo get_options_from_array($themes, $theme); ?>
                        </select>
                    </td>
                </tr>
            </table>
        </div>
        <div class="clear"></div>
        <div class="formbuilder-buttons">
            <input name="submit"  value="Install"  class="btn btn-primary btn-sm"  type="submit"  />
        </div>
    </form>
</div>
<?php

    print_parent_page_bottom();
}

// Do the actual install (create user and update settings)
function do_install()
{
    // check session
    check_nagios_session_protector();

    // get values
    $internal_url = grab_request_var('internal_url', '');
    $admin_name = grab_request_var('admin_name', '');
    $admin_email = grab_request_var('admin_email', '');
    $admin_password = trim(grab_request_var('admin_password', ''));

    $timezone = grab_request_var('timezone', date_default_timezone_get());
    $theme = grab_request_var('theme', 'modern');

    // check for errors
    $errmsg = '';
    if (empty($internal_url))
        $errmsg .= _('URL is blank.') . "\n<br />";
    else if (!valid_url($internal_url))
        $errmsg .= _('Invalid URL.') . "\n<br />";

    if (empty($admin_name))
        $errmsg .= _('Name is blank.') . "\n<br />";

    if (empty($admin_email))
        $errmsg .= _('Email address is blank.') . "\n<br />";
    else if (!valid_email($admin_email))
        $errmsg .= _('Email address is invalid.') . "\n<br />";

    if (empty($admin_password))
        $errmsg .= _('Password is blank.') . "\n<br />";

    // handle errors
    if ($errmsg != '') {
        flash_message($errmsg, 'error');
        return;
    }

    // Make sure there's a superuser (defined by user_id=1)
    if (!is_valid_user_id(1)) {
        $user_id = add_user('nagiosadmin', $admin_password, $admin_name, $admin_email, 1, 1);
        if ($user_id === false) {
            flash_message(_('Unable to create account for ') . 'nagiosadmin', 'error');
            return;
        }
        if ($user_id > 1) {
            set_user_attr('user_id', 1, $user_id);
            $user_id = 1;
        }

        // Make an API key for initial admin
        set_user_attr('api_enabled', 1, $user_id);
        $new_key = random_string(64);

        // Insert key into database
        set_user_attr('api_key', $new_key, $user_id);
    }

    set_option('internal_url', $internal_url);
    set_option('admin_name', $admin_name);
    set_option('admin_email', $admin_email);

    // this has to remain in front of the set_options for install_version and db_version
    update_timezone($timezone);
    
    // set system theme
    set_option('theme', $theme);
    set_user_meta('theme', '', false, $user_id);
    
    // clear license acceptance for nagiosadmin
    set_user_meta($user_id, 'license_version', -1, false);
    set_user_meta($user_id, 'auth_type', "local");

    // clear inital task settings
    set_option('system_settings_configured', 0);
    set_option('security_credentials_updated', 0);
    set_option('mail_settings_configured', 0);

    set_option('install_version', get_product_version());
    set_option('db_version', get_product_release());

    // start the trial
    set_trial_start();

    // delete force install file if it exists
    if (file_exists("/tmp/nagiosfusion.forceinstall")) {
        unlink("/tmp/nagiosfusion.forceinstall");
    }

    // turn on automatic update checks
    set_option('auto_update_check', true);

    // do an update check
    do_update_check(true, true);

    show_install_complete();
}

// Show the final install page with credentials and login link
function show_install_complete($error=false)
{    
    $admin_password = grab_request_var('admin_password', '');

    print_parent_page_top(_('Install Complete'), null, null, null, false);
?>
<script>
    $(function(){ga('send', 'event', 'nagiosfusion', 'Install', 'Complete');});

    // frame buster
    if (top.location != self.location) {
        top.location = self.location.href;
    }
</script>

<div style="margin: 20px 30px;">

    <h1><?php echo _('Install Complete'); ?></h1>

    <p><?php echo _('Congratulations! You have successfully installed Nagios Fusion.'); ?></p>
    <p><?php echo _("You may now login to Nagios Fusion using the following credentials"); ?>:</p>

    <table class="table table-condensed table-no-border table-auto-width">
        <tr>
            <td><?php echo _("Username"); ?>:</td>
            <td><strong>nagiosadmin</strong></td>
        </tr>
        <tr>
            <td><?php echo _("Password"); ?>:</td>
            <td><strong><?php echo $admin_password; ?></strong></td>
        </tr>
    </table>
    <p>
        <a href="login.php" class="btn btn-sm btn-primary" target="_blank" rel="noreferrer">
            <strong>
                <?php echo _('Login to Nagios Fusion'); ?>
            </strong>
        </a>
    </p>
</div>

<?php
    print_parent_page_bottom();
    exit();
}
