#!/usr/bin/perl -w

#
# mkrawindex -- index notes files
# $Id: mkrawindex,v 1.17 2007/02/24 01:25:08 johnh Exp $
#
# Copyright (C) 1994-2006,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 [-X] [file...]
	Writes a raw index to stdout.

	If no files are specified as arguments,
	they are read from stdin.

Option: -X means read the filesname from stdin rather than the command line.

END
    exit 1
}

# old implementation:
# To make an index do:
#    ./mkrawindex /h/local/users/johnh/STUFF/NOTES/9????? |
#	sort -f -t# +1 +0 |
#	sed 's:/h/local/users/johnh:~:' >index

require 5.000;
BEGIN { unshift(@INC, $ENV{'NOTES_BIN_DIR'}); };
use Notes;
use NotesVars;

my($files_from_stdin) = undef;
if ($ARGV[0] eq '-X') {
    $files_from_stdin = 1;
    shift @ARGV;
}

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

my($opthost) = "";
# could be localhost to have urls be file://localhost/foo instead of
# file:///foo.

#
#
#
foreach (@ARGV) {
    &add_file_to_index($_);
}
if ($files_from_stdin) {
    while (<STDIN>) {
	chomp;
        &add_file_to_index($_);
    };
};

exit 0;


sub add_file_to_index {
    my($fn) = @_;

    # "cannonicalize" the filename
    my($cannon_fn) = $fn;
    if ($cannon_fn !~ m@^/@) {
	$cannon_fn = $::notes{dir} . "/" . $cannon_fn;
	$cannon_fn =~ s@^$::notes{home}@/~@;
    };

    my($n) = new Notes($fn);
    my($subs_ref) = $n->subjects();
    if (!defined($subs_ref)) {
	warn "$0: no subjects for file $fn.\n";
	return;
    };
    foreach (@$subs_ref) {
	warn("$0: subject $_ in $fn has leading spaces.\n")
	    if (/^\s$/);
	warn("$0: subject $_ in $fn has trailing spaces.\n")
	    if (/\s$/);
	warn("$0: subject $_ in $fn has an embedded number sign---this will cause problems with prev/next entries.\n")
	    if (/\#/);
        print "file://$opthost$cannon_fn#* $_\n";
    };
}
