#!/usr/bin/php -qC
<?php
#
# Extract fossil configuration card .txt file to subdirectory.
#
# Split up into individual config sections:
#      unpackskin skin.txt dir/
#
# Would create:
#      * dir/name.header
#      * dir/name.footer
#      * dir/name.css
#      * dir/name.th1-setup
#      etc.
#
# Doesn't work on raw -sql or -sql-reg config card files
# (which `mkskin` can create alternatively).
#


# cmd args
$from = $_SERVER["argv"][1];
$skin_name = basename($from, "txt");
$tdir = $_SERVER["argv"][2] or $tdir = ".";
file_exists($tdir) or mkdir($tdir);

# read
$src = file_get_contents($from);

# extract meta name?
if (preg_match("/^#\V+\"([\w.\h-]+)\"/m", $src, $uu)) {
   $skin_name = $uu[1];
}

# find matching config header lines
$rx = "/^config \/config (\d+)\n"
    . "(\d+ '([\w-]+)' value )'/m";
preg_match_all($rx, $src, $uu, PREG_SET_ORDER|PREG_OFFSET_CAPTURE);
foreach ($uu as $row) {

    // rx fields
    list($header, $pos) = $row[0];
    $length = $row[1][0];
    $card = $row[2][0];
    $name = $row[3][0];

    // extract value
    $value = substr($src, $pos + strlen($header), $length - 2 - strlen($card));
    $value = strtr($value, array("''"=>"'"));

    // save to file
    file_put_contents("$tdir/$skin_name.$name", $value);
}

