#!/usr/bin/perl -w
# Copyright (c) 2008--2015 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

use strict;

use File::Find;
use Getopt::Long;

my $usage = "usage: $0 --tree=<sourcetree> [ --target=<target-file> ]"
 . " [ --start-delim=<delimiter> ] [ --end-delim=<delimiter> ] [ --help ]\n";

my $sourcedir = '';
my $target = '';
my $open = '@@';
my $close = '@@';
my $help = '';

GetOptions("tree=s" => \$sourcedir, "target:s" => \$target,
           "start-delim:s" => \$open, "end-delim:s" => \$close) or die $usage;

die $usage unless $sourcedir;

$open = quotemeta $open;
$close = quotemeta $close;
$open = qr/$open/;
$close = qr/$close/;

$sourcedir =~ s(/+)(/)g;
$sourcedir =~ s(/$)();

my $out_fh = \*STDOUT;

if ($target) {
  open(OUT_FH, "> $target") or die "Could not open $target for writing: $!";

  $out_fh = \*OUT_FH;
}


my $time = scalar localtime time;
my $user = (getpwuid($<))[0];
print $out_fh "# file autogenerated by $user run on $time with sourcedir $sourcedir\n\n";

my %conf;
find( { no_chdir => 1, wanted => sub { process_file($sourcedir, \%conf) } }, $sourcedir);

my $last_file = '';
foreach my $match (sort { $a->[0]->[1] cmp $b->[0]->[1] || $a->[0]->[2] <=> $b->[0]->[2] } values %conf) {
  my ($pat, $path, $line) = @{$match->[0]};

  if ($path ne $last_file) {
    print $out_fh "\n\n" unless $path;
    print $out_fh "# Matches from $path\n";
    $last_file = $path;
  }

  print $out_fh "# line $line\n";
  print $out_fh "$pat\[prompt\]=Enter a value for $pat\n";
  print $out_fh "$pat=\n";
}

print $out_fh "\n";

if ($target) {
  close($out_fh);
}

sub process_file {
  my ($sourcedir, $conf) = @_;
  my $full_path = $File::Find::name;

  my $relative_path = $full_path;
  $relative_path =~ s/^$sourcedir//;

  return unless -f "$sourcedir/$relative_path";

  print STDERR "$sourcedir$relative_path\n";

  open IF, "<$sourcedir/$relative_path"
    or die "Cannot open $sourcedir/$relative_path: $!";

  $relative_path =~ s(^/)();
  $relative_path .= "/";

  while (<IF>) {

    # Compatibility - without 'use bytes', the error:
    # "Malformed UTF-8 character" is raised when processing webapp-keyring.gpg.
    use bytes;

    # while (/\G.*$open(.*?)$close/g) {
    # This handles our stuff a little better...
    while (/\G.*?$open(\w+?)$close/g) {
      push @{$conf->{$1}}, [ $1, $relative_path, $. ];
    }
  }

  close IF;
}
