#!/usr/bin/perl

if ($ARGV[0] eq "--help") {
    print "There are no command line options.\n";
    print "The script will prompt you instead\n\n";
    exit;
}

# find perl
print "finding your perl...";
$perl = `which perl`;
if (!$perl) {
    print " can\'t find it\n";
    print "Please enter the path to your perl: ";
    $perl = <STDIN>;
    chomp($perl);
    if (! -x $perl) {
        die "$perl is not executable\n";
    }
}
else {
    print $perl;
    chomp($perl);
}

print "enter directory to install excutable [/usr/local/bin]: ";
$bindir = <STDIN>;
chomp($bindir);
if (!$bindir) {
    $bindir = "/usr/local/bin";
}
if (! -d $bindir) {
	die "$bindir is not a directory\n";
}

print "enter directory to install man page [/usr/local/man/man1]: ";
$mandir = <STDIN>;
chomp($mandir);
if (!$mandir) {
    $mandir = "/usr/local/man/man1";
}
if (! -d $mandir) {
    die "$mandir is not a directory\n";
}

print "enter directory to install midge include files"
	. " [/usr/local/share/midge]: ";
$incdir = <STDIN>;
chomp($incdir);
if (!$incdir) {
    $incdir = "/usr/local/share/midge";
}
if (! -d $incdir) {
	print "\n*** $incdir not found, "
		. "please create it before running make install\n\n";
}

print "Creating midge... ";
open(MDG, ">midge") || die "could not open midge for writing: $!\n";
select(MDG);
print "#!$perl\n\n";
open(SRC, "midge.pl") ||
    die "could not open midge.pl ($!), archive may be corrupted\n";
while(<SRC>) {print;}
close(SRC);
close(MDG);
select(STDOUT);
print "done\n";

print "Creating midi2mg... ";
open(M2M, ">midi2mg") || die "could not open midi2mg for writing: $!\n";
select(M2M);
print "#!$perl\n\n";
open(SRC, "midi2mg.pl") ||
    die "could not open midi2mg.pl ($!), archive may be corrupted\n";
while(<SRC>) {print;}
close(SRC);
close(M2M);
select(STDOUT);
print "done\n";

print "Creating Makefile... ";
open(MF, ">Makefile") || die "could not open Makefile for writing: $!\n";
select(MF);
print "BINDIR=$bindir\n";
print "MANDIR=$mandir\n";
print "INCDIR=$incdir\n\n";

print "install:\n";
print "\tcp midge \$(BINDIR)\n";
print "\tchmod 755 \$(BINDIR)/midge\n";
print "\tcp midge.1 \$(MANDIR)\n";
print "\tchmod 644 \$(MANDIR)/midge.1\n";
print "\tcp midi2mg \$(BINDIR)\n";
print "\tchmod 755 \$(BINDIR)/midi2mg\n";
print "\tcp midi2mg.1 \$(MANDIR)\n";
print "\tchmod 644 \$(MANDIR)/midi2mg.1\n";
print "\tcp include/* \$(INCDIR)\n";
print "\tchmod 644 \$(INCDIR)/*.mgh\n";

select(STDOUT);
close(MF);

print "done\n";
print "Type \`make\' to install\n";
