<?php if (!defined('PmWiki')) exit();
/*
   Author: Martin Fick
   Requires: content.php
   Date: 2008-04-10
*/

define(SCHROOT_CONVERTER, '1.0');
include_once("cookbook/content.php");

// API: Register a SChrootConverter
function SChrootConverterReg($intype, $outtype, $chroot, $cmdfmt,
                                     $cnv=null, $fnc=null)
{
  global $ContentConverters;

  if ($cnv === null)  $cnv = $intype .'2'. $outtype;
  $ContentConverters[$cnv]['cmdfmt']  = $cmdfmt;;
  $ContentConverters[$cnv]['argfnc']  = $fnc;
  $ContentConverters[$cnv]['chroot']  = $chroot;
  ContentRegConverter($intype, $outtype, 'SChrootConverter', $cnv);
}

// API: Upgrade an FSConverter to a SChrootConverter!
function SChrootConverterFS($cnv, $chroot) {
  global $ContentConverters;

  $ContentConverters[$cnv]['fnc'] = 'SChrootConverter';
  $ContentConverters[$cnv]['chroot']  = $chroot;
}


function SChrootConverter($cp, $cnv, $intype, $outtype, $args, $data) {
  global $ContentConverters, $ContentCfgKeep;

  $cnvd = $ContentConverters[$cnv];
  ContentLog($cp, "SChroot Converter: ==== $cnv ====\n");
  $chroot = $cnvd['chroot'];
  $session = substr(shell_exec("schroot -b -c $chroot"),0,-1);
  ContentLog($cp, "Session:$session\n");
  $bdir = substr(shell_exec("schroot --location -c $session"),0,-1);
  ContentLog($cp, "Base Dir:$bdir\n");
  $chdir = "/tmp";

  $cmd = $cnvd['cmdfmt']; $fnc = $cnvd['argfnc'];
  if($fnc) {
    ContentLog($cp, "REPLACING ARGS($args): $cmd\n");
    if($args) {
      $argv = $fnc($cp, $cnv, $intype, $outtype, explode('.', $args));
      $args = implode(" ", ContentEscapeShellArgs($argv));
    }
    $cmd = str_replace('${a}', $args, $cmd);
  }

  $tseg = $cp['tsegs'][count($cp['tsegs']) - 1];
  $iext = $tseg['inext']; $oext = $tseg['ext'];
  $if = "$chdir/I".($iext ? ".$iext" : '');
  $of = "$chdir/O".($oext ? ".$oext" : '');
  $rif = $bdir.$if; $rof = $bdir.$of;
  $cmd = preg_replace('|<\s*\$\{i}|', "< $rif", $cmd);
  $cmd = preg_replace('|>\s*\$\{o}|', "> $rof", $cmd);
  $cmd = str_replace('${i}', $if, $cmd);
  $cmd = str_replace('${o}', $of, $cmd);
  $cmd = "schroot -d $chdir -c $session -r -- $cmd";

  file_put_contents($rif, $data);

  ContentLog($cp, "EXECUTING: $cmd\n");
  exec($cmd, $err);
  if($err) ContentLog($cp, "ERROR:\n".implode("\n", $err)."\n");

  $out = @file_get_contents($rof);
  ContentCachePutFile($cp, $rof);

  if(!$ContentCfgKeep && !$cnvd['keep'])  exec("schroot -e -c $session");

  if(!$out) return ''; // Cache empty results too
  return $out;
}