#!/usr/bin/php -Cq
<?php

// Copyright (c) 1997-now, NeoNova BV, The Netherlands. All rights Reserved.
//
// This software is the copyrighted work of NeoNova BV.
// Use of the software is subject to the general business terms and conditions of NeoNova BV
// and its related transaction documents like license sheets or other written notices.#
// Any reproduction or redistribution of the software not in accordance with the license terms
// is expressly prohibited by law, and may result in severe civil and criminally penalties.
// Violators will be prosecuted to the maximum extent possible.

//  include "/usr/local/astium/web/php/cms/db.php";
//  include "/usr/local/astium/web/php/config.php";

$output = "";
$pos = "";
$message = "";
$language = "";
$fieldname = "";
$name = "";
$subject = "";

function process_line($line, $tablename)
{
  global $output, $pos, $message, $language, $fieldname, $name, $subject;

  if ((substr($line, 10, 4) != "LONG") && ($pos == "atlong")) {
    $message = pg_escape_string(trim($message));
    $subject = pg_escape_string(trim($subject));
    $output .= "DELETE FROM astmessage where name = '$name' and " .
               "language = '$language' and class = 'help';\n";
    $output .= "INSERT INTO astmessage (name, language, class, subject, ascii, html, description) " .
               "VALUES ('$name', '$language', 'help', '$subject', '$message', '$message', '');\n";
    if ($language == 'en') {
      $output .= sprintf("COMMENT ON COLUMN %s IS '%s';\n", $name, $message);
    }
    $message = "";
    $pos = "";
  }
  $wordArray = explode(" ", trim($line));
  if (($wordArray[0] != "CHECK") && (substr($line, 0, 2) != "--")) {
    $fieldname = $wordArray[0];
    $name = "$tablename.$fieldname";
  }
  if (substr($line, 0, 6) == "--HELP") {
    $language = strtolower(substr($line, 7, 2));
    if (substr($line, 10, 4) == "INFO") {
      $subject = trim(substr($line, 15));
    }
    if (substr($line, 10, 4) == "LONG") {
      $message .= substr($line, 15);
      $pos = "atlong";
    }
  }
}

  $fh = file($argv[1]);

  $tablename = basename($argv[1], ".table");
  $output = "";
  $pos = "";
  $message = "";
  $language = "";

  foreach($fh as $line) {
    $wordArray = explode(" ", trim($line));
    if ($wordArray[0] == '\i') {
      $fh2 = file($wordArray[1]);
      foreach($fh2 as $line) {
        process_line($line, $tablename);
      }
    } else {
      process_line($line, $tablename);
    }
  }
  printf("BEGIN;\n");
  printf("%s", $output);
  printf("COMMIT;\n");
?>
