#!/usr/bin/perl

use strict;
use warnings;

# Read in Java source from Gradle file

my $values_file = shift @ARGV;
open my $inp, '<', $values_file;

while( <$inp> !~ /^subprojects/ ) {}

my %variables;
my $content = '';
while( <$inp> ) {
    next if $_ eq "\n";
    last if !/^ /;
    $content .= $_;
    if( /^\s*final String (\S+) = "(.+)"/ ) {
        my( $variable, $value ) = ( $1, $2 );
        for (sort keys %variables) {
            $value =~ s/\$\{$_\}/$variables{$_}/g;
        }
        $variables{$variable} = $value;
    }
}
close $inp;

# FIXME:
$variables{'project.name'} = 'Debian';
$variables{'version'} = '1.2.3';
$variables{'footer'} = '';
$variables{'licenseText'} = 'Apache 2.0';

# Convert read value hash into JSON and extract Debian-relevant part:

die "cannot parse" unless $content =~ /Map<String, Object> expansions = (.*?)Map/ms;

my $json = $1;

for (sort keys %variables) {
    $json =~ s/(:\s*)$_/$1'$variables{$_}'/g;
    $json =~ s/\$\{$_\}/$variables{$_}/g;
}

$json =~ s/\[/{/g;
$json =~ s/\]/}/g;
$json =~ s/,(\s*\})/$1/gms;
$json =~ s/\/\*.*?\*\///gms;
$json =~ s/"(\$\S+)"/\\"$1\\"/g;
$json =~ s/'/"/g;
$json =~ s/jdk \?.*/"true"/;

use JSON;
my $constants = decode_json $json;

my %constants;
for (keys %$constants) {
    if( ref $constants->{$_} ) {
        if( exists $constants->{$_}{deb} ) {
            $constants{$_} = $constants->{$_}{deb};
        } else {
            $constants{$_} = $constants->{$_}{def};
        }
    } else {
        $constants{$_} = $constants->{$_};
    }
}

# Interpret values
use Data::Dumper; print Dumper \%constants;

for my $file (@ARGV) {
    my $content = '';
    open my $inp, '<', $file;
    while( <$inp> ) {
        for my $key (sort keys %constants) {
            s/\$\{$key\}/$constants{$key}/g;
        }
        $content .= $_;
    }
    close $inp;
    open my $out, '>', $file;
    print $out $content;
    close $out;
}
