<?php
/**************************************************************************
* This file is part of the WebIssues Server program
* Copyright (C) 2006 Michał Męciński
* Copyright (C) 2007-2009 WebIssues Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
**************************************************************************/

define( 'VERSION', '0.8.5' );

if( !include_once( 'config/config.inc.php' ) )
    die( '<p><strong>Fatal Error:</strong> The configuration file <tt>config/config.inc.php</tt> does not exist.</p>' );

require_once( 'include/common.inc.php' );

define( 'SCRIPT', 'setup.php' );

$page_titles = array(
    'config' => 'Configuration',
    'tables' => 'Data Tables',
    'name' => 'Server Name',
    'admin' => 'Administrator',
    'types' => 'Issue Types'
);

$action = $_POST[ 'action' ];
$page = '';
$body = '';
$title = 'Setup';

$result = wi_setup_execute();

wi_setup_display_options();

function wi_setup_display_options()
{
    global $page, $body;

    switch ( $page ) {
    case 'name':
        $body .= "<p>Enter server name: <input name=\"name\" /></p>\n";
        break;

    case 'admin':
        $body .= "<p>Login: admin</p>\n";
        $body .= "<p>Enter password: <input type=\"password\" name=\"pwd\" /></p>\n";
        $body .= "<p>Confirm password: <input type=\"password\" name=\"pwd2\" /></p>\n";
        break;
    }
}

function wi_setup_execute()
{
    global $action, $page, $body;
    global $config;

    $page = 'config';

    if ( !wi_check_config() )
        return false;

    $page = 'tables';

    if ( !wi_table_exists( 'server' ) ) {
        if ( $action != 'tables' ) {
            $body .= "<p>Server is configured correctly.</p>\n";
            $body .= "<p>The database tables will be created now.</p>\n";
            return true;
        }

        $queries = wi_read_queries();

        foreach ( $queries as $query ) {
            $query = trim( $query );
            if ( !wi_query( $query ) ) {
                $body .= "<p><strong>ERROR:</strong> Failed to create the database tables.</p>\n";
                return false;
            }
        }

        $body .= "<p>All tables were created successfully.</p>\n";
    }

    $page = 'name';

    $query = 'SELECT db_version FROM {server}';

    $server_row = wi_query_row( $query );

    if ( !$server_row ) {
        if ( $action != 'name' ) {
            $body .= "<p>The server name will be configured.</p>\n";
            return true;
        }

        if ( empty( $_POST[ 'name' ] ) ) {
            $body .= "<p>You have to enter the name of the server.</p>\n";
            return true;
        }

        $uuid = sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
            mt_rand( 0, 0x0fff ) | 0x4000, mt_rand( 0, 0x3fff ) | 0x8000,
            mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ) );

        $query = 'INSERT INTO {server} ( server_name, server_uuid, db_version ) VALUES ( %s, %s, %s )';

        if ( !wi_query( $query, $_POST[ 'name' ], $uuid, VERSION ) ) {
            $body .= "<p><strong>ERROR:</strong> Failed to set the server name.</p>\n";
            return false;
        }

        $body .= "<p>Server name was configured successfully.</p>\n";
    } else if ( $server_row[ 'db_version' ] != VERSION ) {
        $body .= "<p><strong>ERROR:</strong> This server is already configured. Use <a href=\"update.php\">update.php</a> to upgrade the database to a new version.</p>\n";
        $page = 'tables';
        return false;
    }

    $page = 'admin';

    $query = 'SELECT user_id FROM {users} WHERE user_login = %s';

    $admin_row = wi_query_row( $query, 'admin' );

    if ( !$admin_row ) {
        if ( $action != 'admin' ) {
            $body .= "<p>The Administrator user will be created.</p>\n";
            return true;
        }

        if ( empty( $_POST[ 'pwd' ] ) || empty( $_POST[ 'pwd2' ] ) ) {
            $body .= "<p>You have to enter the password for the Administrator user.</p>\n";
            return true;
        }

        if ( $_POST[ 'pwd' ] != $_POST[ 'pwd2' ] ) {
            $body .= "<p>The password was misspelled, please type it again.</p>\n";
            return true;
        }

        $query = 'INSERT INTO {users} ( user_login, user_name, user_passwd, user_access )';
        $query .= ' VALUES ( %s, %s, %s, 2 )';

        if ( !wi_query( $query, 'admin', 'Administrator', md5( $_POST[ 'pwd' ] ) ) ) {
            $body .= "<p><strong>ERROR:</strong> Failed to create the Administrator user.</p>\n";
            return false;
        }

        $body .= "<p>The Administrator user was created successfully.</p>\n";
    }

    $page = 'types';

    $query = 'SELECT type_id FROM {issue_types}';

    $type_row = wi_query_row( $query );

    if ( !$type_row ) {
        if ( $action != 'types' ) {
            $body .= "<p>A set of example issue types will be imported.</p>\n";
            return true;
        }

        $lines = file( wi_make_absolute_path( 'setup/types.ini' ) );
        $types = array();
        $type = null;

        foreach ( $lines as $line ) {
            $line = trim( $line );
            if ( $line == '' || $line{ 0 } == ';' )
                continue;
            if ( $line{ 0 } == '[' ) {
                $type = substr( $line, 1, -1 );
                $types[ $type ] = array();
            } else {
                list( $name, $def ) = explode( '=', $line, 2 );
                $types[ $type ][ $name ] = $def;
            }
        }

        foreach ( $types as $type => $attrs ) {
            $query = 'INSERT INTO {issue_types} ( type_name ) VALUES ( %s )';

            if ( !wi_query( $query, $type ) ) {
                $body .= "<p><strong>ERROR:</strong> Failed to import the issue types.</p>\n";
                return false;
            }

            $type_id = wi_insert_id( 'issue_types', 'type_id' );

            foreach ( $attrs as $attr => $def ) {
                $query = 'INSERT INTO {attr_types} ( type_id, attr_name, attr_def )'
                    . ' VALUES ( %d, %s, %s )';

                if ( !wi_query( $query, $type_id, $attr, $def ) ) {
                    $body .= "<p><strong>ERROR:</strong> Failed to import the issue types.</p>\n";
                    return false;
                }
            }
        }

        $body .= "<p>The issue types were imported successfully.</p>\n";
    }

    $page = '';

    $body .= "<p>This server is configured and working correctly.</p>\n";
    $body .= "<p>Use the WebIssues Client application to access the server.</p>\n";

    return true;
}

require_once( 'include/wizard.inc.php' );
