#!/usr/bin/perl

# EDIT THESE TWO LINES#######################################
my $string_to_add = "SERVERMANAGERSERVER=-YES-";
my $where_to_add = "/etc/hostconfig";
#############################################################


# if the target file already has the key (first part of the string), bail
# otherwise, append the string to add

my $target_disk = $ARGV[2];
my $target_file = $target_disk . $where_to_add;
my @target_file_StatRec = stat($target_file);

if (!-e $target_file) {
	print(STDERR "Couldn't find conf file: " . $target_file . "\n");
	exit 0;
}

# get the key out of the string
$string_to_add =~ m/(.*)=-/;
my $key_to_add = $1;

unless (open(CONFFILE, $target_file)) {
	print(STDERR "Couldn't open conf file: " . $target_file . "\n");
	exit 0;
}

my @conf_lines;

# if the target file has a string in it like the beginning of the string to add, bail
while (<CONFFILE>) {
	my $line = $_;
	push(@conf_lines, $line);
	if ($line =~ /$key_to_add/) {
		print(STDERR "Conf file already has key: " . $key_to_add . "\n");
		close(CONFFILE);
		exit 0;
	}
}

# otherwise, append the string to add

# so first, designate a temp file and a place to back up the original
my $tempFilePath = $target_disk . "/etc/com.apple.installation." . scalar(time());
my $backupPath = $target_file . ".applesaved";

# now stomp the temp file and write the full contents out there
unless (open(TEMPFILE, ">$tempFilePath")) {
	print(STDERR "Couldn't open temp file: " . $tempFilePath . "\n");
	exit 0;
}
print(TEMPFILE @conf_lines);
print(TEMPFILE $string_to_add . "\n");
close(TEMPFILE);

# now give the temp file the right metadata
if(chmod($target_file_StatRec[2], $tempFilePath)) {
	if(chown($target_file_StatRec[4], $target_file_StatRec[5], $tempFilePath)) {
	
		# delete any old backups that may be lurking
		unlink($backupPath);

		# point the backup's file pointer at the current file
		if(link($target_file, $backupPath)) {
			# and rename the temp to the current file name.
			if(rename($tempFilePath, $target_file)) {
				print(STDERR $target_file . "was successfully updated.\n");
			} else {
				print(STDERR "An error occurred attempting to update " . $target_file . ".  The previous file is still active.\n");
			}
		} else {
			print(STDERR "An error occurred attempting to back up " . $target_file . ".  No updating will occur.\n");
		}
	} else {
		print(STDERR "An error occurred setting file ownership for " . $target_file . ".  No updating will occur.\n");
	}
} else {
	print(STDERR "An error occurred setting file mode for " . $target_file . ".  No updating will occur.\n");
}

unlink($tempFilePath);


exit 0;