#! /usr/bin/perl

use warnings;
use strict;

use CGI;
use Scalar::Util qw(isweak);

use JSON;
use Munin::Master::Utils;
use Munin::Common::Defaults;

my $conffile       = $Munin::Common::Defaults::MUNIN_CONFDIR . "/munin.conf";
my $config = munin_config($conffile);


# Header
my $cgi = CGI->new();
print $cgi->header(
	-status => 200, 
	-type => "application/json",
	-expires=>'+5m',
);

# Body
my $json = JSON->new->allow_nonref;

# Remove all recursive refs
remove_weak($config);

print $json->pretty->encode($config);

sub remove_weak {
	my $cur = shift;
	if (ref($cur) eq 'HASH') {
		for my $key (keys %$cur) {
			# Ignore scalars
			next unless ref $cur->{$key};

			my $to_remove = isweak $cur->{$key};
			$to_remove ||= ($key eq "#%#parent");
			$to_remove ||= ($key eq "#%#root");
			# Remove weak refs
			if ($to_remove) {
				delete $cur->{$key};
				next;
			}
			
			# Not weak, go down.
			remove_weak($cur->{$key}) if ref $cur->{$key};
		}
	} elsif (ref($cur) eq 'ARRAY') {
		for (my $i = 0 ; $i < @$cur ; $i++) {
			# Ignore scalars
			next unless ref $cur->[$i];

			# Remove weak refs
			if (isweak $cur->[$i]) {
				delete $cur->[$i];
				next;
			}

			# Not weak, go down.
			remove_weak($cur->[$i]);
		}
	} elsif (ref($cur) eq 'SCALAR') {
		# Ignore scalars
		next unless ref $$cur;

		remove_weak($$cur);
	} else {
		# This cannot be circular, ignoring
	}
}
