#!/usr/bin/perl

use strict;
use warnings;
use feature qw/switch say/;
use Getopt::Long;
use Data::Dumper;
use Tie::IxHash;

my $file;
my $separator = ' ';
my $char_comment = '#';
my $action;

GetOptions(
	'f|file=s' => sub {
		die('Invalid file') unless -f $_[1];
		$file = $_[1];
	},
	'separator=s' => \$separator,
	'char-comment=s' => \$char_comment,
	'generate-vars' => sub { $action = 'vars'; },
	'generate-template' => sub { $action = 'template'; },
	'h|help' => sub { my_usage(); }
);

my_usage() unless (defined $file && -f $file && defined $action);

# We keep insertion order
tie my %all_j2_vars, 'Tie::IxHash';
my $data_new_j2 = '';

open(INPUT, '<', $file);
while(<INPUT>)
{
	chomp;
	given($_)
	{
		when(/^(\s*$|$char_comment)/) {
			$data_new_j2 .= $_ . "\n";
		}
		default {
			my ($k, @v) = split(/[$separator]+/, $_);

			my $j2_var = $k;
			$j2_var =~ s/-/_/g;

			my $tmp_j2_var = $j2_var;

			# If var allready exists... we try a new key => key, key1, key2...
			my $i = 0;
			while(defined $all_j2_vars{$tmp_j2_var})
			{
				$tmp_j2_var = sprintf('%s%d', $j2_var, ++$i);
			}

			$data_new_j2 .= sprintf('%s%s{{ %s }}' . "\n", $k, $separator, $tmp_j2_var);
			$all_j2_vars{$tmp_j2_var} = join($separator, @v);
		}
	}	
}
close(INPUT);


if($action eq 'template')
{
	$data_new_j2 = sprintf("%s\n%s Generated by Ansible\n%s\n\n%s", $char_comment, $char_comment, $char_comment, $data_new_j2);
	say $data_new_j2;
}
else
{
	while (my ($k, $v) = each %all_j2_vars)
	{
		printf("%s: '%s'\n", $k, $v);
	}
}

sub my_usage
{
	say STDERR "Usage: $0 (-f|--file) input_file.conf [ --separator 'string' ] [ --char-comment '#' ]";
	exit 1;
}

