#! /usr/bin/perl -w
# Filename:     gbcnvt3
# Description:  Perl script to convert the guestbook from data file into PostgreSQL
# Author:       imacat <imacat@mail.imacat.idv.tw>
# Date:         2004-09-10
# Copyright:    (c) 2004-2007 imacat

use 5.006;
use strict;
use warnings;
use DBI qw();
use Fcntl qw(:flock);
use File::Basename qw(basename);
use Geo::IP qw(GEOIP_MEMORY_CACHE);
use Getopt::Long qw(GetOptions);
use Net::CIDR::Lite qw();
use Term::ReadKey qw(ReadMode);
# Prototype declaration
sub main();
sub parse_args();
sub try_login($);
sub dh($);
sub country_lookup($);
sub cols($$);
sub update_gbpageno($$);
sub split_page(\@\%$);
sub xfread($);

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

use vars qw($DEFUSER $USER $PGDATABASE $TABLE $FILE $GI $PRIVATE_NETWORKS);
$DEFUSER = exists $ENV{"PGUSER"}? $ENV{"PGUSER"}:
    (getpwuid($>)   or die "$THIS_FILE: getpwuid: $!");
$PGDATABASE = "wov";
$TABLE = "guestbook";
$FILE = "/srv/www/htdocs/$PGDATABASE/magicat/data/$TABLE.dat";
$GI = Geo::IP->new(GEOIP_MEMORY_CACHE);
use constant PRIVATE_CT => "AA";
use constant UNKNOWN_CT => "ZZ";
$PRIVATE_NETWORKS = Net::CIDR::Lite->new(
    qw(10.0.0.0/8 172.16.0.0/12 192.168.0.0/16));

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 guestbook from data file into PostgreSQL

  -U,--username=NAME  Database user name (default: $DEFUSER)
  -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 ($_, %_);
    my ($dbh, $sql, $sth);
    
    # Parse the arguments
    parse_args;
    
    # No longer a working script
    print "Mission completed long time ago.  Program stopped to avoid further problems.\n";
    return;
    
    # Read the data file
    $_ = xfread $FILE;
    
    # Try to log in
    $dbh = try_login "dbi:Pg:dbname=$PGDATABASE;";
    
    $dbh->begin_work                    or die "$THIS_FILE: " . $dbh->errstr;
    
    $sql = "SET NAMES 'utf8';\n";
    $dbh->do($sql)                      or die "$THIS_FILE: $sql: " . $dbh->errstr;
    
    $sql = "LOCK TABLE $TABLE, mtime IN ACCESS EXCLUSIVE MODE;\n";
    $dbh->do($sql)                      or die "$THIS_FILE: $sql: " . $dbh->errstr;
    
    $sql = "TRUNCATE TABLE $TABLE;\n";
    $dbh->do($sql)                      or die "$THIS_FILE: $sql: " . $dbh->errstr;
    
    s/^\s*<table\b[^>]*>\s*//;
    s/\s*<\/table>\s*$//;
    foreach (split /(?<=<\/record>)\s*(?=<record>)/, $_) {
        my ($name, $val, @names, @vals);
        %_ = qw();
        s/^\s*<record\b[^>]*>\s*//;
        s/\s*<\/record>\s*$//;
        foreach (split /(?<=<\/col>)\s*(?=<col name=)/, $_) {
            /^<col name="([^"]+)"[^>]*>([^<]+)<\/col>$/;
            ($name, $val) = ($1, $2);
            $name = "created" if $name eq "date";
            if ($name eq "updatedby") {
                $val = 923153018 if $val eq "imacat";
                $val = 460376330 if $val eq "mandy";
            }
            $_{dh $name} = dh $val;
        }
        $_{"pageno"} = 1;
        $_{"oldpageno"} = 1;
        $_{"updated"} = $_{"created"} if !exists $_{"updated"};
        $_{"updatedby"} = 723676436 if !exists $_{"updatedby"};
        $_{"createdby"} = 723676436 if !exists $_{"createdby"};
        $_{"ct"} = country_lookup $_{"ip"};
        
        foreach (cols $dbh, $TABLE) {
            next unless exists $_{$_};
            push @names, $_;
            if ($_ eq "ip") {
                push @vals, "'$_{$_}'::inet";
            } elsif (/^(?:sn|createdby|updatedby)$/) {
                push @vals, $_{$_};
            } else {
                push @vals, $dbh->quote($_{$_});
            }
        }
        $sql = "INSERT INTO $TABLE"
            . " (" . join(", ", @names) . ") VALUES"
            . " (" . join(", ", @vals) . ");\n";
        $dbh->do($sql)                  or die "$THIS_FILE: $sql: " . $dbh->errstr;
    }
    
    # Update the guestbook page number
    update_gbpageno $dbh, $TABLE;
    
    # Update the mtime
    $sql = "UPDATE mtime SET mtime=now() WHERE tabname='$TABLE';\n";
    $dbh->do($sql)                      or die "$THIS_FILE: $sql: " . $dbh->errstr;
    
    $dbh->commit                        or die "$THIS_FILE: " . $dbh->errstr;
    
    $dbh->disconnect                    or die "$THIS_FILE: " . $dbh->errstr;
    undef $dbh;
    
    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( "username|U=s"=>\$USER,
                    "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 "";
    
    $| = 1 if $VERBOSE > 0;
    
    # Check the arguments
    # We have no arguments
    die "$THIS_FILE: Too many arguments: $ARGV[0]\n$SHORTHELP\n"
        if @ARGV > 0;
    
    return;
}

# try_login: Try to log in, and request the password when required.
sub try_login($) {
    local ($_, %_);
    my ($dsn, $dbh, $subseq, $passwd);
    $dsn = $_[0];
    $subseq = 0;
    # Try to log in
    while (!defined($dbh = DBI->connect($dsn, $USER, $passwd, { PrintError => 0 }))) {
        $_ = DBI->errstr;
        if ($subseq) {
            print STDERR $_;
            sleep 5;
        }
        $subseq = 1;
        # Obtain the current login user
        $USER = $1 if !defined $USER && / failed for user "(.+?)"/;
        # Disable console echo
        ReadMode 2;
        print STDERR defined $USER? "PostgreSQL password for $USER: ":
            "PostgreSQL password: ";
        $passwd = <STDIN>;
        print STDERR "\n";
        die "$THIS_FILE: Failed connecting to the PostgreSQL server\n"
            if !defined $passwd;
        chomp $passwd;
        # Restore console echo status
        ReadMode 0;
    }
    # Return the database handle
    return $dbh;
}

# dh: Un-escape the HTML special character references
sub dh($) {
    local ($_, %_);
    $_ = $_[0];
    s/&quot;/"/g;
    s/&gt;/>/g;
    s/&lt;/</g;
    s/&amp;/&/g;
    return $_;
}

# country_lookup: Look-up country from IP
sub country_lookup($) {
    local ($_, %_);
    my $ip;
    $ip = $_[0];
    # Look up in the GeoIP database
    return uc $_ if defined($_ = $GI->country_code_by_addr($ip));
    # Look up private IP
    return PRIVATE_CT if $PRIVATE_NETWORKS->find($ip);
    # Not known
    return UNKNOWN_CT;
}

# cols: Return the columns of a table (or view)
sub cols($$) {
    local ($_, %_);
    my ($dbh, $table, $sth);
    ($dbh, $table) = @_;
    
    # Get the columns list
    $sth = $dbh->column_info(undef, "public", $table, "%")
        or die "$THIS_FILE: ". $dbh->errstr;
    @_ = qw();
    push @_, ${$_}{"COLUMN_NAME"}
        while defined($_ = $sth->fetchrow_hashref);
    
    return @_;
}

# update_gbpageno: Update the guestbook page number
sub update_gbpageno($$) {
    local ($_, %_);
    my ($dbh, $table, $sql, $sth, $count, $row, $len);
    my (@ents, %sizes, %orig, %pagenos);
    ($dbh, $table) = @_;
    
    # Update the current page number
    # Ge the size of everyhing
    $len = "${table}_len(name, identity, location, email, url, message) AS len";
    # Tavern Backalley has a special table structure
    $len = "char_length(message) AS len"
        if $table eq "garbage";
    $sql = "SELECT sn, $len, pageno FROM $table WHERE NOT hid ORDER BY created;\n";
    $sth = $dbh->prepare($sql);
    $sth->execute;
    $count = $sth->rows;
    for ($_ = 0, @ents = qw(), %sizes = qw(), %orig = qw(); $_ < $count; $_++) {
        $row = $sth->fetchrow_hashref;
        push @ents, $$row{"sn"};
        $sizes{$$row{"sn"}} = $$row{"len"};
        $orig{$$row{"sn"}} = $$row{"pageno"};
    }
    # Split page
    %pagenos = split_page @ents, %sizes, 2560;
    # Update it
    foreach (@ents) {
        next if $orig{$_} == $pagenos{$_};
        $sql = "UPDATE $table SET pageno=$pagenos{$_} WHERE sn=$_;\n";
        $dbh->do($sql);
    }
    
    # Update the old page number
    # Ge the size of everyhing
    $len = "${table}_oldlen(created, ip, host, name, identity, location, email, url, message, updated, updatedby) AS len";
    # Tavern Backalley has a special table structure
    $len = "garbage_oldlen(created, ip, host, message, updated, updatedby) AS len"
        if $table eq "garbage";
    $sql = "SELECT sn, $len, oldpageno FROM $table WHERE NOT hid ORDER BY created;\n";
    $sth = $dbh->prepare($sql);
    $sth->execute;
    $count = $sth->rows;
    for ($_ = 0, @ents = qw(), %sizes = qw(), %orig = qw(); $_ < $count; $_++) {
        $row = $sth->fetchrow_hashref;
        push @ents, $$row{"sn"};
        $sizes{$$row{"sn"}} = $$row{"len"};
        $orig{$$row{"sn"}} = $$row{"oldpageno"};
    }
    # Split page
    # Old page size is always 10240
    %pagenos = split_page @ents, %sizes, 10240;
    # Update it
    foreach (@ents) {
        next if $orig{$_} == $pagenos{$_};
        $sql = "UPDATE $table SET oldpageno=$pagenos{$_} WHERE sn=$_;\n";
        $dbh->do($sql);
    }
    
    return;
}

# split_page: Split page according to the entry sizes
sub split_page(\@\%$) {
    local ($_, %_);
    my ($ents, $sizes, $page_size, $startno, $cursize, %pagenos);
    ($ents, $sizes, $page_size, $startno) = @_;
    $startno = 1 if !defined $startno;
    
    # Bounce for nothing
    return if scalar @$ents == 0;
    
    # Split pages
    %pagenos = qw();
    $pagenos{$$ents[0]} = $startno;
    $cursize = $$sizes{$$ents[0]};
    for ($_ = 1; $_ < scalar(@$ents); $_++) {
        my ($hi_gap, $lo_gap);
        # We need at least one record
        if ($cursize == 0) {
            $pagenos{$$ents[$_]} = $pagenos{$$ents[$_-1]};
            $cursize += $$sizes{$$ents[$_]};
            next;
        # Not oversized yet
        } elsif ($cursize + $$sizes{$$ents[$_]} < $page_size) {
            $pagenos{$$ents[$_]} = $pagenos{$$ents[$_-1]};
            $cursize += $$sizes{$$ents[$_]};
            next;
        }
        $hi_gap = $cursize + $$sizes{$$ents[$_]} - $page_size;
        $lo_gap = $page_size - $cursize;
        # The upper boundary is closer, and the page is not too oversized
        if ($hi_gap < $lo_gap && $hi_gap <= $page_size / 4) {
            $pagenos{$$ents[$_]} = $pagenos{$$ents[$_-1]};
            $cursize += $$sizes{$$ents[$_]};
        # Or, we prefer the lower, since the page is not oversized
        } else {
            $pagenos{$$ents[$_]} = $pagenos{$$ents[$_-1]} + 1;
            $cursize = $$sizes{$$ents[$_]};
        }
    }
    
    return %pagenos;
}

# 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 $_;
        }
    }
}

__END__
