#! /usr/bin/perl -w
# Filename:     gbcnvt
# Description:  Perl script to convert the database format
# Author:       imacat <imacat@mail.imacat.idv.tw>
# Date:         2003-04-06
# Copyright:    (c) 2003-2007 imacat

use 5.008;
use strict;
use warnings;
use Encode qw(from_to FB_CROAK);
use Fcntl qw(:flock :seek);
use File::Basename qw(basename);
use Getopt::Long qw(GetOptions);
# Prototype declaration
sub main();
sub parse_args();
sub convert_dbfile();
sub convert_entry($);
sub find_charset(%);
sub dhc($);
sub h($);
sub dh($);
sub newsn();
sub xfread($);
sub xfupdate($$);

use vars qw($THIS_FILE $VERSION $VERBOSE);
$THIS_FILE = basename($0);
$VERSION = "2.03";
$VERBOSE = 1;

use vars qw($SOURCE $CURRENT $RESULT);
$SOURCE = "/srv/www/htdocs/emily/data/guestbook.txt";
$CURRENT = "/srv/www/htdocs/emily/data/guestbook.dat";
$RESULT = "/tmp/guestbook.dat";
use constant SN_LEN => 9;

use vars qw(@COLUMNS @TRY_CHARSETS %SN $DATE $CURENC);
@COLUMNS = qw(name identity location email url message);
@TRY_CHARSETS = qw(US-ASCII Big5 GB2312 Shift-JIS Big5-HKSCS GB18030);

use vars qw(%SPECIAL_CHARSETS);
%SPECIAL_CHARSETS = (
    "2002-06-06 13:15:09"   => "GB2312",
);

use vars qw($VERMSG $SHORTHELP $HELPMSG);
$VERMSG = "$THIS_FILE v$VERSION by imacat <imacat\@mail.imacat.idv.tw>";
$SHORTHELP = "Try `$THIS_FILE --help' for more information.";
$HELPMSG = << "EOT";
Usage: $THIS_FILE [options]
Convert the database format

  -d,--debug    Display debug messages.  Multiple --debug to debug more.
  -q,--quiet    Disable debug messages.  An opposite that cancels the
                effect of --debug.
  -h,--help     Display this help.
  -v,--version  Display version number.

EOT

main;
exit 0;

# main: Main program
sub main() {
    local ($_, %_);
    
    # Parse the arguments
    parse_args;
    
    # No longer a working script
    print "Mission completed long time ago.  Program stopped to avoid further problems.\n";
    return;
    
    convert_dbfile;
    
    print STDERR "Done.  " . (time - $^T) . " seconds elapsed.\n"
        if $VERBOSE > 0;
    return;
}

# parse_args: Parse the arguments
sub parse_args() {
    local ($_, %_);
    
    # Get the arguments
    eval {
        local $SIG{"__WARN__"} = sub { die $_[0]; };
        Getopt::Long::Configure(qw(no_auto_abbrev bundling));
        GetOptions( "debug|d+"=>\$VERBOSE,
                    "quiet|q"=>sub { $VERBOSE-- if $VERBOSE > 0; },
                    "help|h"=>sub { print $HELPMSG; exit 0; },
                    "version|v"=>sub { print "$VERMSG\n"; exit 0; });
    };
    die "$THIS_FILE: $@$SHORTHELP\n" if $@ ne "";
    
    # Check the arguments
    # We have no arguments
    die "$THIS_FILE: Too many arguments: $ARGV[0]\n$SHORTHELP\n"
        if @ARGV > 0;
    
    return;
}

# convert_dbfile: Convert a database file
sub convert_dbfile() {
    local ($_, %_);
    
    # Gather current S/N
    $_ = xfread $CURRENT;
    $SN{$1} = 1 while s/<col name="sn">(\d+)<\/col>//i;
    
    # Read the source file
    $_ = xfread $SOURCE;
    
    # Find the entries
    s/^\[Guestbook Entry&\]\n//;
    @_ = split /\n+\n\[Guestbook Entry&\]\n/, $_;
    # Convert each entry
    $_ = convert_entry $_ foreach @_;
    # Compose the db file
    $_ = "<table>\n" . join("", @_) . "</table>\n";
    
    # Output the result file
    xfupdate $RESULT, $_;
    
    return;
}

# convert_entry: Convert an entry
sub convert_entry($) {
    local ($_, %_);
    my ($source, $charset, $before, $after);
    $_ = $_[0];
    
    # Preserve the source
    $source = $_;
    
    # Loop for columns
    $_{$1} = dh($2) while s/^([^\n=]+)=([^\n]+)\n//;
    $_{$1} = dh($2) if s/^(message_orig)=\n+(.+)\n(message=)/$3/s;
    $_{$1} = dh($2) if s/^(message)=\n+(.+)//s;
    # Check the required date first
    warn "$THIS_FILE: WARNING: no date:\n$source\n" if !exists $_{"date"};
    $DATE = $_{"date"};
    
    # Check the lost text
    warn "$THIS_FILE: WARNING: $DATE:\nunexpected text:\n$_\n" if $_ ne "";
    
    # Check the other required columns
    warn "$THIS_FILE: WARNING: $DATE:\nno ip:\n$source\n" if !exists $_{"ip"};
    warn "$THIS_FILE: WARNING: $DATE:\nno message:\n$source\n" if !exists $_{"message"};
    
    # Replace the columns with the _orig version, if that exists
    foreach (@COLUMNS) {
        next unless exists $_{$_};
        next unless exists $_{$_ . "_orig"};
        $_{$_} = $_{$_ . "_orig"};
        delete $_{$_ . "_orig"};
    }
    $charset = find_charset %_;
    if (!defined $charset) {
        warn "$THIS_FILE: WARNING: $DATE:\nunknown character set.\n";
    } else {
        foreach (@COLUMNS) {
            next unless exists $_{$_};
            # Skip US-ASCII-only columns
            if ($_{$_} =~ /[\x80-\xFF]/) {
                $before = $_{$_};
                from_to($_{$_}, $charset, "UTF-8", FB_CROAK);
                $after = $_{$_};
                warn "$THIS_FILE: WARNING: $DATE: $charset: $_:\nnot converted.\n"
                    if $before eq $after;
            }
            $_{$_} = dhc $_{$_};
        }
    }
    
    # Compose the columns
    @_ = qw();
    push @_, "<col name=\"sn\">" . h(newsn()) . "</col>";
    push @_, "<col name=\"date\">" . h($_{"date"}) . "</col>";
    delete $_{"date"};
    push @_, "<col name=\"ip\">" . h($_{"ip"}) . "</col>";
    delete $_{"ip"};
    if (exists $_{"host"}) {
        push @_, "<col name=\"host\">" . h($_{"host"}) . "</col>";
        delete $_{"host"};
    }
    foreach (@COLUMNS) {
        next unless exists $_{$_};
        push @_, "<col name=\"$_\">" . h($_{$_}) . "</col>";
        delete $_{$_};
    }
    # Check for lost columns
    warn "$THIS_FILE: WARNING: $DATE:\nunexpected column: $_\n" foreach sort keys %_;
    
    $_ = "<record>\n" . join("\n", @_) . "\n</record>\n";
    
    return $_;
}

# find_charset: Try every charset specified and return the most appropriate one
sub find_charset(%) {
    local ($_, %_);
    my (%source, $charset, $right_charset);
    %source = @_;
    # Special rules
    return $SPECIAL_CHARSETS{$DATE} if exists $SPECIAL_CHARSETS{$DATE};
    foreach $charset (@TRY_CHARSETS) {
        %_ = %source;
        $right_charset = 1;
        foreach (@COLUMNS) {
            next unless exists $_{$_};
            # Try to convert from this character set to UTF-8 first
            eval {
                from_to($_{$_}, $charset, "UTF-8", FB_CROAK);
            };
            # Something wrong here
            if ($@ ne "") {
                $right_charset = 0;
                last;
            }
        }
        return $charset if $right_charset;
    }
    # None found, return nothing
    return;
}

# dhc: De-escape HTML character entities
sub dhc($) {
    local ($_, %_);
    my ($text);
    $text = $_[0];
    $text =~ s/&#(\d{1,5});/
        $_ = pack "v", $1;
        from_to($_, "UTF-16LE", "UTF-8", FB_CROAK);
        $_; /eg;
    return $text;
}

# h: Escape the HTML characters
sub h($) {
    local ($_, %_);
    $_ = $_[0];
    return "" if !defined $_;
    s/&/&amp;/g;
    s/</&lt;/g;
    s/>/&gt;/g;
    s/"/&quot;/g;   # (xgettext) "
    return $_;
}

# dh: De-escape the HTML characters
sub dh($) {
    local ($_, %_);
    $_ = $_[0];
    return "" if !defined $_;
    s/&quot;/"/g;   # (xgettext) "
    s/&gt;/>/g;
    s/&lt;/</g;
    s/&amp;/&/g;
    return $_;
}

# newsn: Generate a new S/N
sub newsn() {
    local ($_, %_);
    my ($min, $max, $int, $sn);
    
    $min = 10 ** (SN_LEN - 1);     # 100000000
    $max = (10 ** SN_LEN) - 1;     # 999999999
    $int = $max - $min + 1;
    
    do {
        # Generate a random serial number
        $sn = $min + int rand $int;
    } until !exists $SN{$sn};
    
    $SN{$sn} = 1;
    
    return $sn;
}

# xfread: Read from a file
sub xfread($) {
    local ($_, %_);
    my ($FH, $file);
    $file = $_[0];
    
    # Return as lines
    if (wantarray) {
        open $FH, $file                 or die "$THIS_FILE: $file: $!";
        flock $FH, LOCK_SH              or die "$THIS_FILE: $file: $!";
        @_ = <$FH>;
        flock $FH, LOCK_UN              or die "$THIS_FILE: $file: $!";
        close $FH                       or die "$THIS_FILE: $file: $!";
        return @_;
    
    # A scalar file content
    } else {
        # Regular files
        if (-f $file) {
            my $size;
            @_ = stat $file             or die "$THIS_FILE: $file: $!";
            $size = $_[7];
            return "" if $size == 0;
            open $FH, $file             or die "$THIS_FILE: $file: $!";
            flock $FH, LOCK_SH          or die "$THIS_FILE: $file: $!";
            read $FH, $_, $size         or die "$THIS_FILE: $file: $!";
            flock $FH, LOCK_UN          or die "$THIS_FILE: $file: $!";
            close $FH                   or die "$THIS_FILE: $file: $!";
            return $_;
        
        # Special files
        } else {
            open $FH, $file             or die "$THIS_FILE: $file: $!";
            flock $FH, LOCK_SH          or die "$THIS_FILE: $file: $!";
            $_ = join "", <$FH>;
            flock $FH, LOCK_UN          or die "$THIS_FILE: $file: $!";
            close $FH                   or die "$THIS_FILE: $file: $!";
            return $_;
        }
    }
}

# xfupdate: Update a file
sub xfupdate($$) {
    local ($_, %_);
    my ($FH, $file, $content);
    ($file, $content) = @_;
    
    if (-e $file) {
        open $FH, "+<$file"             or die "$THIS_FILE: $file: $!";
        flock $FH, LOCK_SH              or die "$THIS_FILE: $file: $!";
        $_ = join "", <$FH>;
        if ($_ ne $content) {
            seek $FH, 0, SEEK_SET       or die "$THIS_FILE: $file: $!";
            truncate $FH, 0             or die "$THIS_FILE: $file: $!";
            print $FH $content          or die "$THIS_FILE: $file: $!";
        }
        flock $FH, LOCK_UN              or die "$THIS_FILE: $file: $!";
        close $FH                       or die "$THIS_FILE: $file: $!";
    
    } else {
        open $FH, ">$file"              or die "$THIS_FILE: $file: $!";
        flock $FH, LOCK_EX              or die "$THIS_FILE: $file: $!";
        print $FH $content              or die "$THIS_FILE: $file: $!";
        flock $FH, LOCK_UN              or die "$THIS_FILE: $file: $!";
        close $FH                       or die "$THIS_FILE: $file: $!";
    }
    return;
}

__END__
