#!/usr/bin/perl -w
# -*- perl -*-

#
# Author: Slaven Rezic
#
# Copyright (C) 2005,2014,2018,2021 Slaven Rezic. All rights reserved.
# This program is free software; you can redistribute it and/or
# modify it under the same terms as Perl itself.
#
# Mail: slaven@rezic.de
# WWW:  http://www.rezic.de/eserte/
#

use strict;
use lib "."; # for perl with PERL_USE_UNSAFE_INC=0
use Data::Dumper;
use Getopt::Long;

my $package;
my $prefix;
my $rerun_notice;
my @orig_ARGV = @ARGV;
GetOptions("package=s" => \$package,
	   "prefix=s" => \$prefix,
	   "rerun-notice=s" => \$rerun_notice,
	  ) or die "usage!";
my $mod = shift || die "Please specify module to dump";

eval 'require $mod'; die $@ if $@;
$package = $mod if !defined $package;

my $stash = eval '\%' . $package . '::';

my $vars = {};
while(my($k,$v) = each %$stash) {
    for my $type (qw(SCALAR ARRAY HASH)) {
	my $code = $v."{$type}";
	my $x = eval $code;
	if (!$@ && $x) {
	    if (ref $x eq 'SCALAR') {
		$vars->{$k} = $$x;
	    } else {
		$vars->{$k} = $x;
	    }
	}
    }
}

if (!defined $rerun_notice) {
    $rerun_notice = "$^X $0 @orig_ARGV";
}

my $out = "";
$out .= "[% PERL -%]\n";
$out .= "# DO NOT EDIT. Instead edit the source $mod\n";
$out .= "# and re-run the following command:\n";
$out .= "#\n";
$out .= "#    $rerun_notice\n";
$out .= "#\n";
for my $k (sort keys %$vars) {
    my $v = $vars->{$k};
    my $v_s = Data::Dumper->new([$v],[''])->Useqq(1)->Indent(1)->Dump;
    $v_s =~ s/^.*?=\s*//;
    $v_s =~ s/;\n?\z//;
    my $full_var;
    if (defined $prefix && $prefix ne "") {
	$full_var = $prefix . ".";
    }
    $full_var .= $k;
    $out .= '$stash->set("' . $full_var . '", ' . $v_s . ');' . "\n";
}
$out .= "[% END -%]\n";

print $out;

__END__
