#!/usr/bin/perl -s

$tmpfile = "/tmp/editdb.$$";
$EDITOR = "vi";
if ($ENV{'EDITOR'}) {
    $EDITOR = $ENV{'EDITOR'};
}
use MBGD::DB;
use File::Copy;
use File::Compare;

if (! $table || ! $key) {
	die "Usage: $0 -DB=dbname -table=tablename -key=keyname -value=value\n";
}
die "table name not specified\n" if (! $table);
die "key name not specified\n" if (! $key);

$db = MBGD::DB->new($DB);
die "Can't connect to $DB as user $user\n" if (! $db);


print STDERR "select * from $table where $key='$value'\n";

$sth = $db->prepare("select * from $table where $key='$value'");
$sth->execute;

open(W, ">$tmpfile");
$a = $sth->fetchrow_hashref;
foreach $k (keys %{$a}) {
	print W "[$k]\t$a->{$k}\n";
}
close(W);
copy($tmpfile, "$tmpfile.BCK");
system("$EDITOR $tmpfile");
if (compare($tmpfile, "$tmpfile.BCK") == 0) {
	unlink($tmpfile);
	unlink("$tmpfile.BCK");
	print STDERR "File not changed\n";
	exit(0);
}
print "OK? ";
$ans = <STDIN>;
if ($ans =~ /^[yY]/) {
	open(R, $tmpfile) || die;
	while (<R>) {
		chomp;
		($k, $d) = split(/\t/);
		$k =~ s/\[(.*)\]/\1/;
		$b->{$k} = $d;
	}
	foreach $k (keys %{$b}) {
		print("update $table set $k='$b->{$k}' where $key='$value'\n");
		$sth = $db->prepare(
			qq{update $table set $k="$b->{$k}" where $key='$value'});
		$sth->execute;
	}
}
unlink($tmpfile);
