#!/usr/bin/perl -w

#
# notesinit
# Copyright (C) 1996-2002,2012  Free Software Foundation, Inc.
# $Id: notesinit,v 1.12 2006/01/14 22:52:56 johnh Exp $
#

sub usage {
    print STDERR <<END;
usage: $0 [-D]

This program sets up notes mode for the first time.
It typically runs interactively.

Options:
    -D	    use all defaults (also turns off prompting)
END
    exit 1;
}

require 5.000;
use strict;
use Getopt::Long;

my(%opts);
&GetOptions(\%opts, qw(D));
&usage if ($#ARGV >= 0 && $ARGV[0] eq '-?');
my($use_defaults) = defined($opts{'D'});

my($PERL) = $^X;  # location of perl executable


use POSIX;
BEGIN { unshift(@INC, $ENV{'NOTES_BIN_DIR'}); };
use NotesVars;
use strict;


sub query {
    my($lc) = 1;
    if ($_[0] eq '-nolc') {
	$lc = undef;
	shift @_;
    };
    my($expl, $query, $valid_regexp, $default) = @_;
    return $default if ($use_defaults);
    print $expl;
    my($a);
    for (;;) {
        print $query;
        $a = <>;
	chomp $a;
	$a = lc($a) if ($lc);
        return $default if ($a eq '');
        return $a if ($a =~ /$valid_regexp/);
	print "I didn't understand your answer `$a'.\n";
    };
}

my($expl);
$expl =  <<END;
notesinit will set up notes-mode for the first time.

What is notes mode?  Texinfo documentation should be installed on your
system.  Documentation is also available on the web at
<http://www.isi.edu/~johnh/SOFTWARE/NOTES_MODE/>.  Everything you will
be asked here is discussed in greater detail in the documentation.

END

my($home_dir) = ((getpwuid($<))[7]);
my($def_choices, $def) = ('(Y/n)', 'y');
if (-f "$home_dir/.notesrc") {
    die "$0: will not override existing .notesrc with -D option.\n"
	if ($use_defaults);
    ($def_choices, $def) = ('(y/N)', 'n');
    print "WARNING:  you already appear to have notes configured.\n\n"
};

my($a) = query($expl, "Do you want to set up notes mode now $def_choices? ", '(y|n)', $def);
if ($a ne 'y') {
    print "\nnotesinit exited.\n\n";
    exit 1;
};

$expl = <<END;

Notes are stored in two-level hierarchy of directories.
For example:
~/NOTES/199603/960329
               ^^^^^^-- a notes file (the date, in YYMMDD)
        ^^^^^^--------- one subdirectory per month (form: YYYYMM)
  ^^^^^---------------- the parent directory of everything

END
$::notes{dir} = query("-nolc", $expl, "What should the parent directory be (default: ~/NOTES)? ", '.', '~/NOTES');
# fix ~  (in honor of Cliffette's "yes, I have no tilde")
$::notes{dir_notilde} = $::notes{dir};
$::notes{dir_notilde} =~ s@^~/@$home_dir/@;
$::notes{dir} =~ s@^$home_dir/@~/@;


my($now) = time;
my($today_pathname) = epoch_to_pathname($now);

$expl = <<END;

notesinit can now set-up your environment for notes.
It will take the following steps:

0. set up your .notesrc
1. create $::notes{dir}
2. create a sample note for today ($today_pathname)
3. index the default note
4. set up a crontab entry to re-index notes at 4am every morning
    (by running mkall)

END
($def_choices, $def) = ('(M/d/s)', 'm');
($def_choices, $def) = ('(m/D/s)', 'd') if (-f "$home_dir/.notesrc");
my($go) = query($expl, "Make these changes, describe the changes, or stop $def_choices? ", '[mds]', $def);
exit 1 if ($go eq 's');

sub commands {
    my($expl, $cmd) = @_;
    print $expl if (!$use_defaults);
    if ($go eq 'm') {
	system($cmd);
    } else {
	print "$cmd\n";
    };
}

#
# Ok, the code below is less-than-ideal.
# It's somewhat silly to have Perl output the shell commands
# rather than just "do it".
# The reason is that we to allow the user to look at what's being done.
#

$expl = "\n### changes begin here\n" . 
    "\n### 0. set up your .notesrc\n";
commands($expl, "cat >$home_dir/.notesrc <<END
dir: $::notes{dir}
END
");

$expl = "\n### 1. creating $::notes{dir}\n";
commands($expl, "mkdir -p $::notes{dir_notilde};\nchmod 0700  $::notes{dir_notilde}\n");

my($heading) = strftime_epoch("%d-%b-%y %A", $now);
my($underline) = "-" x length($heading);
$expl = "\n### 2. create a sample note for today ($today_pathname)\n";
commands($expl, "mkdir -p `dirname $today_pathname`;\n cat >$today_pathname <<END

$heading
$underline

* Today
-------

to do list goes here?


* Environment/notes
-------------------

Set up notes with notesinit.

(To read the manual, run   info notes-mode .)

END
");

my($mkall) = $PERL . " " . $::notes{bin_dir} . "/mkall";
my($crontab_entry) = "0 4 * * * $mkall";

$expl = "\n### 3. index the default note\n";
commands($expl, $mkall);

$expl = "\n### 4. set up a crontab entry to re-index notes at 4am every morning\n";
my($tmpfile) = "$home_dir/notesinit.$$~";
# this whole touch thing is to avoid leaving a globally writable crontab
commands($expl, "touch $tmpfile;
chmod 0600 $tmpfile;
echo 'If you do not have a crontab, errors about not being able to open a cron table can be ignored.';
crontab -l | sed 's/^\\(.*\\/mkall\\)\$/# \\1/' >>$tmpfile;
echo '$crontab_entry' >>$tmpfile;
" . $::notes{bin_dir} . "/setcrontab $tmpfile
rm -f $tmpfile");

print "\n### changes end here\n" if (!$use_defaults);

print "\nYou have elected to have the changes DESCRIBED but not made.\n" .
	"To make the changes yourself, run the commands between\n" .
	"\"changes begin here\" and \"changes end here\".\n"
	if ($go eq 'd');

exit 0;
