#!/usr/bin/perl

use Getopt::Std;
use File::Basename;
use File::Copy;
use strict;

my (@headers, @libraries, $destinclude, $destlib, @installed);
our ($opt_m, $opt_i, $opt_l, $opt_h);

getopts('mi:l:h');

# set defaults
$destinclude = $opt_i || "/usr/include/djb";
$destlib     = $opt_l || "/usr/lib";

help() if ($opt_h);

# see if everyting's okay before proceeding
if ($opt_m) {
	mkdir $destlib || die "Can't make destination include directory $destinclude $!\n";
	help();
}
help( "Destination directory '$destinclude' does not exist, please make!\n")
	unless (-d $destinclude);
help("Can't find destination lib directory '$destlib' $!\n")
	unless (-d $destlib);

# the headers and libraries we're going to install
chomp(@headers = <DATA>);
@libraries = map { "./$_/$_.a" }
  qw( buffer byte sig unix timeout alloc dns tai );

# install the headers
foreach my $file (@headers) {
	my $newfile = "$destinclude/" . basename($file);
	copy ($file, $newfile) || die "Can't copy $file to $newfile $!\n";
	push @installed, $newfile;
}

# install the archives.  Note that we change the name of the files
# from unix.a to libdjbunix.a .  This is so that you can just say
# "-ldjbunix" in your compile statement.  The "djb" bit is in there
# so I won't clobber a "liballoc.a" out there.
foreach my $file (@libraries) {
	# ./unix/unix.a -> /usr/lib/libdjbunix.a
	my $newfile = "$destlib/libdjb" . basename($file);
	copy ($file, $newfile) || die "Can't copy $file to $newfile $!\n";
	push @installed, $newfile;
}

# print out all that we've installed
print "Installed these files:\n";
foreach (@installed) {
	print "$_\n";
}

sub help {
	my $msg = shift;
	print "$msg\n\n" if ($msg);
print <<EOF;
Use of program:
$0 -m -i [includedir] -i [libdir]
-i [dir] : your include directory, currently set to $destinclude
-l [dir] : your lib directory, currently set to $destlib
-m       : mkdir djb lib ($destinclude) if it doesn't exist
EOF
	die;
}

__DATA__
./unix/alloc.h
./buffer/byte.h
./buffer/exit.h
./unix/open.h
./byte/scan.h
./buffer/str.h
./byte/uint32.h
./buffer/buffer.h
./buffer/error.h
./byte/fmt.h
./buffer/readwrite.h
./unix/seek.h
./buffer/strerr.h
