#!/local/bin/php -q
<?
    //
    // Adds contents of a file after the body tag
    // warning this does NOT check if you allready added something !!
    //

function add_fragment ($infile, $fragment_file) {
    $i = 0;
    $done = FALSE;
    $fp = fopen($infile, "r");
    if ($fp > 0) {
      // read the file in
	
      while (!feof($fp)) {
	$buf = fgets($fp, 256);
	
	if (!$done && (eregi("<body", $buf))) {
	    $output[$i] = $buf;
	    $i++;
	    // now insert
	    $fp2 = fopen($fragment_file, "r");
	    if ($fp2 > 0) {
		// read the file in
		while (!feof($fp2)) {
		    $buf = fgets($fp2, 256);
		    $output[$i] = $buf;
		    $i++;
			}
		$done=1;
	    }
	}
	else {
	    // or write the same line
	    $output[$i] = $buf;
	}
	$i++;
      }
      fclose($fp);

      $fp = @fopen($infile, "w");
      if ($fp > 0) {
	  // spit out the array
	  for ($n = 0; $n < $i; $n++) {
	      // echo $output[$n];
	      fputs($fp, $output[$n]);
	  }
	  fclose($fp);
	  echo "\nMade ALL requested changes, let's hope they are ok !\n";
      }
    }
}

function usage ($user_input) {
  echo (" I got:
   $user_input\n ");
  echo ("Usage:
add_header html-file fragment_to_add
   html_file: the file to which you want to append a header
   fragment_to_add: the file to insert
");
}

echo "\n\nPHP add program\n*******************\n";


if ( isset($argv[1]) == 0 ) {
  $input = $argv[1];
  usage ($input);
  exit;
}
else $infile = $argv[1];

if ( isset($argv[2]) == 0 ) {
  $input = $argv[1] . " " . $argv[2] ;
  usage ($input);
  exit;
}
else {
    $infile = $argv[1];
    $fragment_file = $argv[2];

    if (!file_exists($infile)) {
	echo "\nWARNING: The html file '$infile' does NOT exist !\n";
    }
    elseif (!file_exists($fragment_file)) {
	echo "\nWARNING: The fragment file '$fragment_file' does NOT exist !\n";
    }
    else {
	add_fragment ($infile, $fragment_file);
    }
}

?>
