#!/usr/bin/perl -w

package esmith;

use strict;
use Errno;
use esmith::DB::db;
use IO::File;
use English;
use JSON;

my %ENV;

my @d = `bash -c 'source $ARGV[0] && echo db=\${db:-configuration}'`;
for my $item (@d) {
    chomp $item;
    print "ITEM: $item \n";
    my ( $k, $v ) = split /=/, $item, 2;
    $v =~ s/^(['"])(.*)\1/$2/;    #' fix highlighter
    $v =~ s/\$([a-zA-Z]\w*)/$ENV{$1}/g;
    $v =~ s/`(.*?)`/`$1`/ge;      #dangerous
    $ENV{$k} = $v;
}

my $db = esmith::DB::db->open( $ENV{'db'} ) || die("{}");
my @items = $db->get_all();
my %out;
foreach my $item (@items) {
    my %props = $item->props();
    if ( scalar( keys %props ) <= 1 ) {
        $out{ $item->key } = $props{'type'};
    }
    else {
        $out{ $item->key } = { $item->props() };
    }
}

print encode_json \%out;