#!/usr/bin/perl -w

# This script is only moderatly smart. It assumes that any semicolon at the
# end of a line and not in a string is the end of a statement. C comments
# not supported right now.

# Note: the data is stored as one long string with embedded NULLs between
# the statements and an extra NULL at the end. I did this rather than an
# array of strings because arrays of strings require one relocation record
# per string. Yes, I've been listening to Ulrich Drepper.

# The code to read it would be:
# string = dlsym( module, "__PG_INSTALL_FUNCTION" );
# while( *string )
# {
#   Process( string );
#   string += strlen(string) + 1;
# }

my $output = <<EOF;
static const char *__PG_INSTALL_SCRIPT =
EOF

while(<>)
{
  chomp;
  s/--.*//g;
  next if /^\s*$/;

  s/^\s+//;
  s/\s+$//;
  
  $string .= " ".$_;
  
  if( $string =~ /;\s*$/ and not inString( $string ) )
  {
    $string =~ s/([\\"])/\\$1/g;
    
    $output .= "  \"$string\" \"\\0\"\n";
    $string = "";
  }
}

$output .= "  \"\\0\";\n";

print $output.<<EOF;
const char *__PG_INSTALL_FUNCTION()
{
  return __PG_INSTALL_SCRIPT;
}
EOF

exit;

sub inString
{
  my $str = shift;
  
  for(;;)
  {
    if (not $str =~ /^(([^\'\"\$]|\\[\'\"\$])+)(\'|\"|\$\w*\$)(.*)/ )
    { return 0 }
    # In string now
    $sep = $3;
    $str = $4;

#    print ">>$sep,$str\n";    
    if (not $str =~ /^(.*?)\Q$sep\E(.*)/ )
    { return 1 }

#    print ">$str\n";    
    $str = $2;
  }
}
