#!/usr/bin/perl -w

# jedstate-to-gdbmrecent: migrate from jedstate to gdbmrecent databases
# Copyright (C) 2007  Rafael Laboissiere

# This script is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

=head1 NAME

jedstate-to-gdbmrecent - migrate from jedstate to gdbmrecent databases

=head1 SYNOPSIS

    jedstate-to-gdbmrecent [JEDSTATE-DB [GDBMRECENT-DB]]

=head1 DESCRIPTION

B<jedstate-to-gdbmrecent> is a tool to help users to mirate from a
jedstate database into a gdbmrecent one.  It can be called with 0, 1
or 2 arguments.  When present, the first and second arguments are the
file names of the jedstate database (defaults to F<~/.jedstate.db>)
and the gdbmrecent one (defaults to F<~/.jed/recent_db>).  If
C<GDBMRECENT-DB> does not exist, then it will be created.  Otherwise,
the contents of C<JEDSTATE-DB> will be added to it.

In order to use the gdbmrecent database, install the jed-extra Debian
package and add the following to your F<~/.jed/jed.rc> initialization
file (or whichever name it has):

    require ("gdbmrecent");

=head1 SEE ALSO

L<jed (1)>

=head1 AUTHOR

Rafael Laboissiere

=cut

use GDBM_File;

(my $prog = $0) =~ s{.*/}{};

die "Usage: $prog [~/.jedstate.db [~/.jed/recent_db]]"
  if $#ARGV > 1;

my $jedstate_db = ($#ARGV >= 0 ? $ARGV [0] : "$ENV{HOME}/.jedstate.db");
my $gdbmrecent_db = ($#ARGV == 1 ? $ARGV [1] : "$ENV{HOME}/.jed/recent_db");

tie %jedstate, 'GDBM_File', $jedstate_db , &GDBM_READER, 0644
  or die "$prog: Cannot open file $jedstate_db for reading\n";

tie %gdbmrecent, 'GDBM_File', $gdbmrecent_db , &GDBM_WRCREAT, 0644
  or die "$prog: Cannot open file $gdbmrecent_db for reading/writing\n";

while ((my $k, $v) = each %jedstate) {
  ## Remove trailing ^@ character, stored by jedstate
  $k = substr ($k, 0, -1);
  $v = substr ($v, 0, -1);
  ## Store values : jedstate is <column>\t<line>\t<time>
  ##                gdbmrecent is <time>:<line>:<column>
  $gdbmrecent {$k} = join (":", reverse (split (/\s+/, $v)));
}

untie %jedstate;
untie %gdbmrecent;
