#!/usr/bin/perl -w
use strict;

##
# Personal Preferences - alter these if you think you know what you're doing but
#                        it's best to just to leave them alone.
##
# -------------------------------------------------------------------------------------
#  The download site automatically grabs the tarballs from djb's web site. If you don't 
#  like that, download them yourself and place them in $src.
#
#  $service is where you store symlinks to your services for easy managability. I
#  like mine in /service. It's the default location and it makes it very convenient to 
#  restart a supervised program like dnscache (svc -t /service/dnscache).
# -------------------------------------------------------------------------------------

my $src  = "/usr/local/src";			# where we want to store our sources
my $name  = "DJBware";				# what to call the Service
my $service = "/service";			# the control directory for svscan
my $dl_site = "http://cr.yp.to";
my $qm_site = "http://www.qmail.org";
#my $dl_site = "http://matt.simerson.net/computing/dns/djbdns";

##
# MacOS X Dependencies - don't change these
##

my $start = "/Library/StartupItems";		# where to put the OS X startup scripts
my $spl   = "StartupParameters.plist";		# Property List filename
my $ds    = "/System/Library/StartupItems/DirectoryServices";

## 
# system specific settings, there should seldom be a reason to change these
##
my $curl    = "/usr/bin/curl";
my $diff    = "/usr/bin/diff";
my $tar     = "/usr/bin/tar";
my $install = "/usr/bin/install";

##
# package names - don't change these without good reason
##
my $ucs = "ucspi-tcp-0.88";
#my $dt  = "daemontools-0.70";
my $dt  = "daemontools-0.76";
my $dns = "djbdns-1.05";

my $user = (getpwuid ($<))[0];
if ( $user ne "root") { die "Thou must haveth root to proceed!\n"; };

if ( !-e $src ) { mkdir("$src",0775) || die "can't create $src: $!"; };
chdir($src) or die "can't cd to $src: $!";

&fetch_files( $ucs, $dt, $dns, $dl_site);
&install_ucspi( $ucs );
&install_daemontools( $dt );
&install_djbdns( $dns );
&configure_start();

exit 0;

sub configure_start {
	if ( !-e $service ) { 
		mkdir ($service, 0755) || die "can't create $service: $!\n"; };
	if ( !-e $start ) { 
		mkdir ($start, 0755) || die "can't create $start: $!\n" };
	if ( !-e "$start/$name" ) {
		mkdir("$start/$name", 0755) || die "can't create $start/$name: $!\n"; };
	&create_the_Startup_Item( "$start/$name/$name", "$start/$name/$spl", "$start/$name/$spl\.ds", "$ds/$spl" );
};

sub create_the_Startup_Item {
	# http://www.opensource.apple.com/projects/documentation/howto/html/SystemStarter_HOWTO.html
	# http://www.osxfaq.com/Tutorials/LearningCenter/HowTo/Startup/index.ws
	if ( !-e $_[0] ) {
		print "create_the_Startup_Item: creating $_[0]\n";
		open (EXEC, ">$_[0]") or die "Unable to open $_[0]: $!\n";
			print EXEC "\#!/bin/sh\n\# Services Startup File\n";
			print EXEC "\# Generated by Matt Simerson\n\n\#\#\n";
			print EXEC "\# Start up svscan and supervised programs in $service\n";
			print EXEC "\#\#\n\nPATH=/usr/local/bin:/usr/sbin:/usr/bin:/bin\n";
			print EXEC "export PATH\n\ncase \"\$1\" in\nstart)\n";
			print EXEC "\tif [ ! -f /var/run/svscan.pid ]\n\tthen\n";
			print EXEC "\t\techo -n \"Starting services: svscan\"\n";
			print EXEC "\t\tcd /service\n\t\tenv - PATH=\"\$PATH\" svscan &\n";
			print EXEC "\t\techo \$! > /var/run/svscan.pid\n";
			print EXEC "\t\tfor dir in `ls /service`\n\t\tdo\n\t\t\techo -n \" \$dir\"\n";
			print EXEC "\t\tdone\n\t\techo \"\.\"\n\telse\n\t\t";
			print EXEC "echo \"It appears svscan is already running\. NOT starting!\"\n";
			print EXEC "\tfi\n\t;;\nstop)\n\t";
        		print EXEC "echo -n \"Stopping services: svscan\"\n";
			print EXEC "\tkill `cat /var/run/svscan\.pid`\n\trm /var/run/svscan\.pid\n";
			print EXEC "\tfor dir in `ls /service`\n\tdo\n\t\techo -n \" \$dir\"\n";
			print EXEC "\t\tsvc -dx /service/\$dir\n\t\tsvc -dx /service/\$dir/log\n";
			print EXEC "\tdone\n\techo \"\.\"\n\t;;\nesac\n";
		close (EXEC);
		chmod(00755, $_[0]);
	} else {
		print "create_the_Startup_Item: already installed ($_[0])\n";
	};
	if ( !-e $_[1] ) {
		print "create_the_Startup_Item: creating $_[1]\n";
		open (PLIST, ">$_[1]") or die "Unable to open $_[1]: $!\n";
			print PLIST "{\n  Description     = \"DJB Services\";\n";
  			print PLIST "  Provides        = (\"DNS\");\n";
  			print PLIST "  Requires        = (\"Network Configuration\");\n";
  			print PLIST "  Uses            = (\"Network Configuration\");\n";
  			print PLIST "  OrderPreference = \"Early\";\n";
  			print PLIST "  Messages =\n  {\n";
    		print PLIST "    start = \"Starting DJB Services\";\n";
    		print PLIST "    stop  = \"Stopping DJB Services\";\n";
    		print PLIST "    restart = \"Restarting DJB Services\";\n";
			print PLIST "  };\n}\n";
		close (PLIST);
	} else {
		print "create_the_Startup_Item: already installed ($_[1])\n";
	};

	if ( !-e $_[2] ) {
		print "create_the_Startup_Item: creating $_[2]\n";
		open (PLIST, ">$_[2]") or die "Unable to open $_[2]: $!\n";
			print PLIST "{\n  Description     = \"directory services\";\n";
  			print PLIST "  Provides        = (\"NetInfo\", \"NIS\");\n";
  			print PLIST "  Requires        = (\"Portmap\", \"Network Configuration\");\n";
  			print PLIST "  OrderPreference = \"None\";\n";
  			print PLIST "  Messages =\n  {\n";
    		print PLIST "    start = \"Starting directory services\";\n";
    		print PLIST "    stop  = \"Stopping directory services\";\n";
			print PLIST "  };\n}\n";
		close (PLIST);
	} else {
		print "create_the_Startup_Item: already installed ($_[2])\n";
	};

	if ( !-e "$_[3]\.backup" ) {
		#print "backing up \t$_[3]\n\tto\t$_[3]\.backup\n";
		#system "cp $_[3] $_[3]\.backup";
		#print "showing the diffs...\n\n";
		#system "$diff $_[2] $_[3]";
		#print "done.\n\n";
		#print "Installing $_[3]\n";
		#system "cp $_[2] $_[3]\.backup";
		#print "\n  NOTE: This diffs should be one line, reflecting the change\n";
		#print "  removing Resolver from the Directory Services Packing List\n\n";
		#print "  Any other differences should be addressed now.\n";
	};
};

sub install_djbdns {
	if ( !-e "/usr/local/bin/dnscache" ) {
		print "install_djbdns: installing\n";
		if ( -e "$src/$_[0]" ) {
			chdir("$src/$_[0]") or die "can't cd to $src/$_[0]: $!\n";
			system "echo 'cc -O2' > conf-cc";
			system "echo 'cc -Xlinker -x' > conf-ld";
			system "make setup check";
		} else {
			print "Hey, where's my source directory?\n";
		};
	} else {
		print "install_djbdns:       already installed\n";
	};
};

sub install_daemontools {
	if ( $_[0] eq "daemontools-0.70" ) {
		if ( !-e "/usr/local/bin/svscan" ) {
			print "install_daemontools: installing\n";
			if ( -e "$src/$_[0]" ) {
				chdir("$src/$_[0]") or die "can't cd to $src/$_[0]: $!\n";
				system "echo 'cc -O2' > conf-cc";
				system "echo 'cc -Xlinker -x' > conf-ld";
				system "make setup check";
			} else {
				print "Hey, where's my source directory?\n";
			};
		} else {
			print "install_daemontools:  already installed\n";
		};
	} elsif ( $_[0] eq "daemontools-0.76" ) {
		if ( !-e "/usr/local/bin/svscan" ) {
			print "install_daemontools: installing\n";
			if ( -e "$src/admin/$_[0]/src" ) {
				chdir("$src/admin/$_[0]/src") or die "can't cd to $src/admin/$_[0]/src: $!\n";
				system "echo 'cc -O2' > conf-cc";
				system "echo 'cc -Xlinker -x' > conf-ld";
				system "echo '/usr/local/bin' > home";
				system "make";
				&install_daemontools_manual( "$src/admin/$_[0]/package/commands" );
			} else {
				print "Hey, where's my source directory?\n";
			};
		} else {
			print "install_daemontools:  already installed\n";
		};
	};
};

sub install_ucspi {
	if ( !-e "/usr/local/bin/tcpserver" ) { 
		print "install_ucspi: installing\n";
		if ( -e "$src/$_[0]") {
			chdir("$src/$_[0]") or die "can't cd to $src/$_[0]: $!\n";
			system "echo 'cc -O2' > conf-cc";
			system "echo 'cc -Xlinker -x' > conf-ld";
			if ( !-e "ucspi-rss.diff" ) { 
				system "$curl -O $qm_site\/ucspi-rss.diff";
				system "patch -p1 < ucspi-rss.diff";
			 };
			system "make setup check";
		};
	} else {
		print "install_ucspi:        already installed\n";
	};
};


sub fetch_files {
	if ( !-e $_[0] ) { 
		if ( $_[3] eq "http://cr.yp.to" ) {
			system "$curl -O $dl_site/ucspi-tcp/$_[0]\.tar.gz";
			system "$tar -xzf $_[0]\.tar\.gz";
		} else {
			system "$curl -O $dl_site\/$_[0]\.tar.gz";
			system "$tar -xzf $_[0]\.tar\.gz";
		};
	};
	if ( !-e "admin/$_[1]"  ) { 
		if ( $_[3] eq "http://cr.yp.to" ) {
			system "$curl -O $dl_site/daemontools/$_[1]\.tar\.gz";
			system "$tar -xzf $_[1]\.tar\.gz";
		} else {
			system "$curl -O $dl_site\/$_[1]\.tar.gz";
			system "$tar -xzf $_[1]\.tar\.gz"; 
		};
	};
	if ( !-e $_[2] ) { 
		if ( $_[3] eq "http://cr.yp.to" ) {
			system "$curl -O $dl_site/djbdns/$_[2]\.tar.gz";
			system "$tar -xzf $_[2]\.tar\.gz";
		} else {
			system "$curl -O $dl_site\/$_[2]\.tar\.gz";
			system "$tar -xzf $_[2]\.tar\.gz"; 
		};
	};
};

sub install_daemontools_manual {
	my $file = $_[0];
	if (-r $file) {
		open(INPUT,$file); 
		while (<INPUT>) { 
			chomp $_; 
			system "$install $_ /usr/local/bin";
		};
		close INPUT;
	};
};
