#! /usr/bin/perl

use utf8;
use CGI (':standard');
use DBI;
use Encode;
use MIME::Words;

print header(-type => "text/html",  -charset => "utf-8");

print "<html><body>\n";
my $orig = russian_utf8();
print "<p>$orig (starting value)</p>\n";

my $dbh;
eval {
    $dbh = DBI->connect('dbi:mysql:test:127.0.0.1:3341',
        'test', undef, {RaiseError => 1});

    $dbh->do("set names utf8");
    $dbh->do("drop table if exists t");
    $dbh->do(<<"EOF");
create table t (
    id int unsigned not null auto_increment primary key,
    t char(40) character set utf8,
    word char(40) character set utf8
)
EOF
    $dbh->do("insert into t (t, word) values ('x $orig x', '$orig')");

    my $v = $dbh->selectall_arrayref(<<"EOF")->[0][0];
select t from t
where t regexp concat('[[:<:]]', word, '[[:>:]]')
order by id limit 0, 1
EOF
    if (defined $v) {
        print "<p>$v (flag not set, no binmode)</p>\n";
        print "<hr /><p>setting binmode utf8</p>\n"; binmode(STDOUT, ":utf8");
        print "<p>orig == v</p>\n" if $orig == $v;
        print "<p>$v (flag not set, binmode)</p>\n";
        Encode::_utf8_on($v);
        print "<p>$v (flag set, binmode)</p>\n";
    }
    else {
        print "<p>No data returned from query</p>\n";
    }
};

my $error = $@;
if ($error) {
    print qq(<p class="error">ERROR: $error</p>\n);
}

print "</body></html>\n";

exit(0);

sub chinese_utf8 {
    my $text = '=?gb2312?B?Rlc6INTGxM/Cw9PO0MXPoqOh?=';
    my $utf8;
    foreach (MIME::Words::decode_mimewords($text)) {
        my $value = $_->[0];
        Encode::from_to($value,($_->[1] || 'iso-8859-1'), "utf8");
        $utf8 .= decode(($_->[1] || 'iso-8859-1'),$_->[0]);
    }

    return $utf8;
}

#sub russian_cp1251 {
#    return '';
#}

sub russian_utf8 {
    return 'радиовещательная';
}
