#!/usr/bin/perl -w
#
# Script to convert wwv_database old format (abstime) to 
# new format (date) for CLX 4.05
#
# I hope all situations covered - DL6RAI Tue Feb  9 21:49:10 GMT 1999

$home = (getpwnam('clx_us'))[7];
$tmp  = "$home/tmp";
$inf  = "$tmp/wwv_data";
$outf = "$tmp/wwv_data.neu";

%month  = ('Jan',1,'Feb',2,'Mar',3,
           'Apr',4,'May',5,'Jun',6,
           'Jul',7,'Aug',8,'Sep',9,
	   'Oct',10,'Nov',11,'Dec',12);

chdir $home;
if ( ! -d "$tmp" ) { mkdir "$tmp",oct(777); }
chmod 0777,$tmp;

$rc = system("psql clx_db -c \"\"");
# print "RC=$rc\n";

if ( $rc !=0 ) {
	print "Postmaster not running or not accessible.\n";
	exit;
}

$r = `psql clx_db  -qtc "select distinct attname,atttypid \
	from pg_attribute where attname='wwv_date'"`;
$r =~ s/\s//g;
$attrtype = (split(/\|/,$r))[1];

# 702 seems to be type "abstime"
if ( $attrtype != 702 ) {
	print "WWV data is already converted.\n";
	exit;
}

# Although we are delivering a new wwv_data.cl file, in any
# case this repairs the old one.
open(IN,"< db/wwv_data.cl");
open(OUT,"> db/wwv_data.cl.new");
while(<IN>) {
	if (/abstime/) { s/abstime/date/; }
	print OUT $_;
}
close(IN);
close(OUT);

rename ("db/wwv_data.cl","db/wwv_data.cl.old");
rename ("db/wwv_data.cl.new","db/wwv_data.cl");

if ( ! -d $tmp ) {
	mkdir($tmp,777);
} else {
	chmod(0777,$tmp);
}

$cmd = sprintf("psql clx_db -c \"copy wwv_data to \'%s\'\"",$inf);
# print "+ $cmd\n";
system($cmd);

open(IN,"sort $inf |") || die "Cannot open wwv_data.\n";
open(OUT,"> $outf");

$last = "";
while(<IN>) {
	next if /invalid/i;
	@r = split /\t/;
	($lm,$d,$y) = (split(/\s/,$r[0]))[1,2,4];
	$m = $month{"$lm"};
	$r[0] = sprintf("%02d-%02d-%04d",$m,$d,$y);
	$current = join("|",(@r)[0..5]);
	if ( $last ne $current ) {
		$out = join("\t",@r);
		print OUT "$out";
		$last = $current;
	}
}
close(IN);
close(OUT);

$cmd = "psql clx_db -c \"drop table wwv_data\"";
# print "+ $cmd\n";
system($cmd);

$cmd = "psql clx_db < $home/db/wwv_data.cl";
# print "+ $cmd\n";
system($cmd);

$cmd = sprintf("psql clx_db -c \"copy wwv_data from \'%s\'\"",$outf);
# print "+ $cmd\n";
system($cmd);

$cmd = "psql clx_db < $home/db/wwv_data.idx";
# print "+ $cmd\n";
system($cmd);
