#!/usr/bin/perl -w

#
# mkconfig
# $Id: mkconfig,v 1.10 2003/05/23 16:26:30 johnh Exp $
#
# Copyright (C) 1996,2012  Free Software Foundation, Inc.
# Comments to <johnh@isi.edu>.
#
# This file is under the Gnu Public License, version 2.
# For details see the COPYING which accompanies this distribution.
#

sub usage {
    print STDOUT <<END;
usage: $0 [elisp|perl]
END
    exit 1;
}

require 5.000;
use strict;

&usage if ($#ARGV != 0 || $ARGV[0] eq '-?');


my($type) = $ARGV[0];
&usage if ($type ne 'elisp' && $type ne 'perl');


my($home_dir) = ((getpwuid($<))[7]);

my(%defaults) = (
    'dir'	=> ['path', '~/NOTES'],
    'int_form'	=> ['form', '%Y%m'],
    'file_form'	=> ['form', '%y%m%d'],
    );
$defaults{'bin_dir'} = ['path', "$ENV{'NOTES_BIN_DIR'}"]
    if defined($ENV{'NOTES_BIN_DIR'});

my($key, $value, %notes);
while (($key, $value) = each %defaults) {
    $notes{$key} = $value->[1];
}

#
# open the file
#
my($notesrc) = "$home_dir/.notesrc";
$notesrc = $ENV{'NOTESRC'} if (defined($ENV{'NOTESRC'}));

if (open (CONFIG, "<$notesrc")) {
    while (<CONFIG>) {
        next if (/^\s*#/);
        next if (/^\s*$/);
        next if (/^\s*exec/);
        ($key, $value) = /^\s*([^:]+):\s*(.*)$/;
        $notes{$key} = $value;
        die("$0: file_form cannot be changed from %y%m%d.\n")
    	if ($key eq 'file_form' && $value ne '%y%m%d');
    };
    close CONFIG;
};

#
# generate extra forms
#
my(%old_notes) = %notes;
while (($key, $value) = each %old_notes) {
    next if ($key eq '');

    # fix forms
    if ($defaults{$key}->[0] eq 'form') {
	my($oldkey, $oldvalue) = ($key, $value);
	$key =~ s/_form/_glob/;
	$value =~ s/%Y/[12][90][0-9][0-9]/g;
	$value =~ s/%(y|m|d)/[0-9][0-9]/g;
	$notes{$key} = $value;

	my($key, $value) = ($oldkey, $oldvalue);
	$key =~ s/_form/_regexp/;
	$value =~ s/%Y/[12][90]([0-9][0-9])/g;
	$value =~ s/%(y|m|d)/([0-9][0-9])/g;
	$notes{$key} = $value;
    };
};
$notes{'url_prefix'} = "file:///$notes{'dir'}/";

#
# output
#
#if ($type eq 'perl') {
#} else {
#};
my($comment) = ($type eq 'perl' ? '# ' : '; ');
print "$comment automatically generated by $0\n";
while (($key, $value) = each %notes) {
    next if ($key eq '');

    # normalize stuff
    if (defined($defaults{$key}) && $defaults{$key}->[0] eq 'path') {
	# not absolute or ~, then it's in notes_dir.
	$value = "$notes{'dir'}/$value" if ($value !~ m@^[~/]@);
	# fix ~
        $value =~ s@^~/@$home_dir/@;
    };

    if ($type eq 'perl') {
	print "\$notes{'$key'} = '$value';\n";
    } else {
	$key =~ s/_/-/g;
	$value =~ s/([()])/\\\\$1/g if ($key =~ /-regexp$/);
	print "(defvar notes-$key \"$value\")\n";
    };
};

exit 0;

