#!/usr/bin/perl

##################################################################
# Copyright (c) 2002 Jaap G Karssenberg. All rights reserved.    #
# This program is free software; you can redistribute it and/or  #
# modify it under the same terms as Perl itself.                 #
#                                                                #
# This script is a frontend to the Zoidberg module, it starts    #
# the Zoidberg perl shell.                                       #
#                                                                #
# mailto:j.g.karssenberg@student.utwente.nl                      #
# http://zoidberg.sourceforge.net                                #
##################################################################

use strict;
use Zoidberg;
use Getopt::Long qw(:config gnu_compat no_getopt_compat no_ignore_case);
use Pod::Usage;

#print "Debug: ARGV is: --".join('--', @ARGV)."--\n";
 
# get info
my @passwd = getpwuid($>);
# Returns ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell).

##### CONFIG #####
my $prefix	= '/usr/local/';	# prefix to zoidberg files
my $skel_dir	= '/etc/zoid/';		# path to default config file
my $dir 	= $passwd[7].'/.zoid/';	# users personal dir
##################

#############################
#### Parse basic options ####
#############################

my $message = $Zoidberg::LONG_VERSION."\n\nSee also <http://zoidberg.sourceforge.net>\n";
my ($help, $version, $exec_string, $interact_opt, $script, $argv) = (0, 0, '', -1, "",[@ARGV]);

GetOptions(
	'help|?|usage'		=> \$help,
	'exec|command=s'	=> \$exec_string,
	'version'		=> \$version,
	'interaction!'		=> \$interact_opt,
) || pod2usage( {
        '-message' => $message,
        '-verbose' => 0,
        '-exitval' => 1,
} );

if ($help) {
	pod2usage( {
		'-message' => $message,
		'-verbose' => 1,
		'-exitval' => 0,
	} );
}
elsif ($version) {
	print $Zoidberg::LONG_VERSION."\n";
	exit 0;
}

my $interact;
unless ($interact_opt < 0) { $interact = $interact_opt; }
elsif (!$exec_string) { $interact = (-t STDIN) && (-t STDOUT); }
else { $interact = 0; }
#print "debug: interact: $interact, interact_opt: $interact_opt, string: $exec_string\n";

############################
#### prepare for launch ####
############################

# check ARGV
# TODO let ARGV (in caps) pass GetOpt::Long
if ((-f $argv->[0])&&(!$argv->[1])) { $exec_string .= ($exec_string ? ' ; ' : '').'_source '.$argv->[0]; }

# copy skel
my $first_time = 0;
unless (-e $dir) {
	dircopy($skel_dir, $dir);
	mkdir $dir.'var/';
	mkdir $dir.'plugins/';
	$first_time = 1;
}

# set env
$ENV{USER} = $passwd[0];
$ENV{HOME} = $passwd[7];
push @INC, $dir.'plugins';

# check for login shell
unless ($ENV{PWD}) { $ENV{PWD} = $passwd[7]; }

my $fluff_conf = {
	'prefix' => $prefix,
	'config_dir' => $dir,
	'config_file' => 'profile.pd',
	'core_file' => 'core.pd',
	'grammar_file' => 'grammar.pd',
	'cache_file' => 'var/cache.pd',
	'interactive' => $interact,
};

########################
#### AND Lift-off ! ####
########################

my $cube = Zoidberg->new;
if ($interact) {
	$cube->init($fluff_conf);
	if ($exec_string) { $cube->parse($exec_string); }
	$cube->main_loop;
}

else {
	$cube->silent;
	$cube->init($fluff_conf);
	if ($exec_string) { $cube->parse($exec_string); }
}

my $exit = $cube->round_up ? 1 : 0;

exit $exit;

#######################
#### helpfull subs ####
#######################

sub dircopy {
	# dir from, dir to
	my ($from, $to) = @_;
	$from =~ s/\/?$/\//;
	$to =~ s/\/?$/\//;
	print "Copying $from to $to\n";
	unless (-e $to) { mkdir($to) || die "Could not create dir $to"; }
	opendir FROM, $from || die "Could not open dir $from";
	my @files = readdir FROM;
	closedir FROM;
	shift @files; #.
	shift @files; #..
	foreach my $file (grep {-f $from.$_} @files) {
		open IN, $from.$file || die "Could not open file ".$from.$file." to read";
		open OUT, '>'.$to.$file  || die "Could not open file to ".$to.$file." write";
		while (<IN>) { print OUT $_; }
		close OUT;
		close IN;
	}
	foreach my $dir (grep {(-d $from.$_)&&($_ ne 'CVS')} @files) {
		dircopy( $from.$dir, $to.$dir ); #recurs
	}
}

__END__

=head1 NAME

    zoid - a frontend script to the Zoidberg shell

=head1 SYNOPSIS

    zoid [options]

    Options:
       --help           Detailed help message
       --exec           execute string
       --command        does the same as --exec
       --version        display version information
       --interaction    start interactive shell
       --nointeraction  execute non-interactive

    See also F<man zoid>

=head1 OPTIONS

Abbreviations of options are also allowed.

=over 4

=item B<-h, --help, -u, --usage>

    Print a this help message and exits.

=item B<-e, --exec>

    Execute string as interpreted by zoidberg.
    If non-interactive exits with exit status
    of command string.

=item B<-c, --command>

    Does the same as exec.

=item B<-v, --version>

    Display version information.
    The displayed version is the version of the
    Zoidberg module, not of the program files.

=item B<-i, --interaction>

    Start an interactive shell.
    This is the default if no exec string is
    supplied. If exec string is supplied
    nointeraction becomes default.

=item B<--nointeraction>

    Do not start interactive shel - just
    execute commandline options and exit.

=back

=cut
