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

// create the views

function fix_quotes($msg) {
  $result = str_replace("\'", "'", $msg);
  $result = str_replace('\"', '"', $result);
  $result = str_replace('"', '\"', $result);
  return $result;
}

function remove_dupe_blanks($text) {
  $result = str_replace('        ', ' ', $text);
  $result = str_replace('       ', ' ', $result);
  $result = str_replace('      ', ' ', $result);
  $result = str_replace('     ', ' ', $result);
  $result = str_replace('    ', ' ', $result);
  $result = str_replace('   ', ' ', $result);
  $result = str_replace('  ', ' ', $result);
  return $result;
}

$debug = 0;

function Debug($level, $msg) {
  global $debug;

  if ($debug >= $level) {
    printf("%s\n", $msg);
  }
}

  $i = 0;
  $create = "-- Copyright (c) 1997-now, Use The Source BV, The Netherlands. All rights Reserved.
--
-- This software is the copyrighted work of Use The Source BV.
-- Use of the software is subject to the general business terms and conditions of Use The Source 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.

--    schemaname     |          tablename           | tableowner | tablespace | hasindexes | hasrules | hastriggers 
----------------------+------------------------------+------------+------------+------------+----------+-------------
-- information_schema | sql_features                 | postgres   |            | f          | f        | f

CREATE VIEW pg_tables AS SELECT
  'main' as schemaname, name as tablename, 'owner' as tableowner, '' as tablespace, 'f' as hasindexes, 'f' as hasrules, 'f' as hastriggers 
  FROM sqlite_master
  WHERE type = 'table'
;

";

  $fh = file('astium.views');
  foreach($fh as $lineno => $line) {
    if ($lineno < $i) continue; // skip previously processed lines (while reading ahead)
    $line = trim($line);
    if (substr($line, 0, 2) == "--") continue;
    if (trim($line) == '') continue; 
    $wordArray = explode(" ", $line);
    if ($wordArray[0] != 'CREATE') continue;
    $work = $line;
    for ($i = $lineno+1; substr(trim($work), -1) != ';' ;$i++) {
      $work .= ' ' . $fh[$i];
    }
    $create .= fix_quotes(remove_dupe_blanks($work));
    $create .= "\n";
  }
  echo $create;

?>
