#!/usr/bin/php
<?php

if (!is_array($GLOBALS['argv'])) {
    echo "\n";
    echo "Can't read command line arguments\n";
    echo "\n";
    exit(1);
}

$CAMPSITE_DIR = dirname(dirname(__FILE__));
$GLOBALS['g_campsiteDir'] = $CAMPSITE_DIR;
$ETC_DIR = $CAMPSITE_DIR . '/conf';

require_once("cli_script_lib.php");

if (!camp_is_readable("$ETC_DIR/install_conf.php")) {
    exit(1);
}

// include install_conf.php file
require_once("$ETC_DIR/install_conf.php");

$usage =
"  Usage:
  newscoop-utf8-converter [--help] [--log] [--silent] [--force] \
                          --charset=[from_charset]|--default_charset

  This script will convert all of your website character and text
  data in database to utf8 character set.

  Parameters:
    --help
        Show this help and exit.

    --log=LOG_FILE
        Records the sql queries in the specified file.

    --silent
        Don't display any messages on success.

    --force
        Dont prompt, assume 'yes' to questions.

    --charset=[from_charset]
        Specify the character set from which to convert to UTF8.

    --default-charset
        Convert from the database server character set to UTF8.

    --list-charsets
        List all available charsets and exit.

  See also:
      newscoop-backup
      newscoop-restore

";


$silent = false;
$force = false;
$listCharsets = false;
$charset = null;
$useDefaultCharset = false;

// gets the arguments from command line, if any
for ($i = 1; isset($GLOBALS['argv'][$i]); $i++) {
    $option = explode('=', $GLOBALS['argv'][$i]);
    switch ($option[0]) {
        case '--log':
            $log_file = !empty($option[1]) ? rtrim($option[1], '/') : '';
            if (empty($log_file)) {
                echo "Error: Log file not specified!\n\n";
                echo $usage;
                exit(1);
            }
            break;
        case '--silent':
            $silent = true;
            break;
        case '--force':
            $force = true;
            break;
        case '--charset':
            $charset = $option[1];
            break;
        case '--default-charset':
            $useDefaultCharset = true;
            break;
        case '--list-charsets':
            $listCharsets = true;
            break;
        case '--help':
            echo $usage;
            exit(0);
        default:
            echo "Error: Invalid option '" . $option[0] . "'!\n\n";
            echo $usage;
            exit(1);
    }
}

if (!$silent) {
    echo "\n";
    echo "Newscoop UTF8 Converter Utility\n";
    echo "-------------------------------\n";
}

if (!is_file("$ETC_DIR/database_conf.php")) {
    if (!$silent) {
        camp_exit_with_error("Database configuration file is missing!");
    }
    exit(1);
}
require_once("$ETC_DIR/database_conf.php");
camp_connect_to_database();

if ($listCharsets) {
    echo "The list of available charsets:\n";
    $charsetsList = camp_get_all_charsets();
    foreach ($charsetsList as $charsetName=>$charsetDescription) {
        echo "- $charsetName: $charsetDescription\n";
    }
    exit(0);
}

if ($useDefaultCharset) {
    $charset = camp_get_server_charset();
}
if (empty($charset)) {
    if (!$silent) {
        camp_exit_with_error('Please specify the charset!');
    }
    exit(1);
}
if (!camp_valid_charset($charset)) {
    if (!$silent) {
        camp_exit_with_error("Invalid charset '$charset'!");
    }
    exit(1);
}

if (!$force) {
    if ($silent) {
        exit(1);
    }
    echo "\nWARNING! The conversion to UTF-8 may break your database content!\n";
    echo "If you broke your database content it can not be recovered unless\n";
    echo "you restore the database from a backup!\n\n";
    echo "It is strongly recommended that you back up your Newscoop instance\n";
    echo "before performing the conversion!\n\n";
    echo "Do you want to continue the conversion now? (y/N): ";
    if (strtolower(trim(camp_readline())) != 'y') {
        echo "Conversion aborted by the user!\n";
        exit(1);
    }
}

if (empty($ETC_DIR)) {
    if (!$silent) {
        echo $usage;
    }
    exit(1);
}

if (!$silent) {
    echo "UTF8 Converter script version: ".$Campsite["VERSION"]."\n";
    echo "Converting the database from '$charset' to 'UTF-8'...\n";
}

$dumpFile = $Campsite['DATABASE_NAME']."-database-$charset.sql";
camp_backup_database($Campsite['DATABASE_NAME'], $dumpFile, $output,
                     array("--default-character-set=$charset"));
$outDumpFile = $Campsite['DATABASE_NAME'].'-database-utf8.sql';
camp_change_dump_encoding($dumpFile, $outDumpFile, $charset);
camp_restore_database($outDumpFile, $silent);
$skipped = array();
$res = camp_utf8_convert(null, $skipped);
if ($res !== true) {
    camp_exit_with_error($res);
}
unlink($dumpFile);
unlink($outDumpFile);

if (!$silent && count($skipped) > 0) {
    echo "
Encountered non-critical errors while converting data to UTF-8 encoding!
The following database queries were unsuccessful because after conversion
text values become case insensitive. Words written in different case were
unique before the conversion; after the conversion they are identical,
breaking some constraints in the database.

The upgrade script can not fix these issues automatically!

You can continue to use the data as is and manually fix these issues
later. The table fields that were not converted will not support case
insensitive searches.

Please save the following list of skipped queries:\n";
    foreach ($skipped as $query) {
        echo "$query;\n";
    }
    echo "-- end of queries list --\n";
}

if (!$silent) {
    echo "done.\n\n";
    echo "IMPORTANT!\n";
    echo "You must restart the apache server for the changes to take effect!\n";
}

exit(0);

?>
