#!/usr/bin/php
<?php

// Plugin install script.
// 2011-08-25 Some refinements

function install_plugin( $plugin_file) {
  $plugin_name = basename( $plugin_file, ".plg");

  echo "installing plugin: $plugin_name", PHP_EOL;

  // parase plugin definition XML file
  $xml = simplexml_load_file( $plugin_file, NULL, LIBXML_NOCDATA);
  if ($xml === FALSE) {
    echo " xml parse error", PHP_EOL;
    return FALSE;
  }

  //print_r($xml);
  //echo $xml->asXML();

  // download/create all the files
  foreach ($xml->FILE as $file) {
    $name = $file->attributes()->Name;
    echo " file $name: ";
    
    // ensure parent directory exists
    if (!file_exists( dirname( $name))) {
      if (!mkdir( dirname( $name), 0770, true)) {
	echo "unable to create directory", PHP_EOL;
	return FALSE;
      }
    }
    
    // if file already exists, no need to download/create
    if (file_exists( $name)) {
      echo "already exists", PHP_EOL;
    }
    
    // for local file, just copy it
    else if ($file->LOCAL) {
      if (!copy( $file->LOCAL, $name)) {
	echo "unable to copy LOCAL file", PHP_EOL;
	return FALSE;
      }
      echo "successfully copied LOCAL file", PHP_EOL;
    }
    
    // for inline file, create with inline contents
    else if ($file->INLINE) {
      $handle = fopen( $name, "w");
      if (!$handle) {
	echo "unable to create file", PHP_EOL;
	return FALSE;
      }
      if (!fwrite( $handle, trim( $file->INLINE).PHP_EOL)) {
	echo "unable to write file", PHP_EOL;
	return FALSE;
      }
      fclose( $handle);
      echo "successfully wrote INLINE file contents", PHP_EOL;
    }
    
    // for download file, download and verify the file MD5
    else if ($file->URL) {
      echo "downloading from $file->URL ... ";
      system( "wget -nv -O $name $file->URL", $retval);
      if ($retval) {
	echo "bad download, deleting", PHP_EOL;
	unlink( $name);
	return FALSE;
      }
      if ($file->MD5) {
	if (md5_file( $name) != $file->MD5) {
	  echo "bad MD5, deleting", PHP_EOL;
	  unlink( $name);
	  return FALSE;
	}
      }
      echo "success", PHP_EOL;
    }
    
    // if file has 'Mode' attribute, apply it
    if ($file->attributes()->Mode) {
      $mode = $file->attributes()->Mode;
      if (!chmod( $name, octdec( $mode))) {
	echo "  chmod failure", PHP_EOL;
	return FALSE;
      }
      echo "  successfully changed file mode", PHP_EOL;
    }
    
    // if file has 'Run' attribute, run specified command with file as argument
    if ($file->attributes()->Run) {
      $command = $file->attributes()->Run;
      echo "  $command $name ... ";
      system( "$command $name", $retval);
      if ($retval) {
	echo "failed", PHP_EOL;
	return FALSE;
      }
      echo "success", PHP_EOL;
    }
  }
  echo " plugin successfully installed", PHP_EOL;
  return TRUE;
}

$usage = <<<EOF
Usage: installplg <plugin_filename>
  
installplg is used to install a .plg plugin xml file.

EOF;

// Gittyup
if ($argc != 2) echo $usage;
else            install_plugin( $argv[1]);
?>
