#!/usr/bin/perl

use strict;
use warnings;

use Piny;

my ( $reponame, $attr, $value ) = @ARGV;

if ( not defined $reponame ) {
  die "Usage: $0 reponame|--user [tweakable [value]]\n";
};

my $config;

if ( $reponame eq "--user" ) {
  $config = Piny::Environment->instance->user->config;
} else {
  $config = Piny::Repo->new( $reponame )->config;
};

if ( not defined $attr ) {

  my $tweakables = $config->all_tweakables;

  foreach my $t ( sort keys %$tweakables ) {
    my $v = $tweakables->{$t};
    if ( defined $v ) {
      print "$t => $v\n";
    } else {
      print "$t undefined\n";
    };
  };

} else {

  $attr = lc $attr;
  $attr =~ s/\./_/g;

  if ( defined $value ) {
    undef $@;
    eval {
      $config->$attr( $value );
    };
    if ( $@ ) {
      print STDERR "$attr is not a legal tweakable, or $value is not a legal value for that tweakable.\n$@\n";
    };
    if ( $value ne $config->$attr ) {
      print STDERR "Failed to set $attr (perhaps an override is in place)\n";
    };
  };

  undef $@;
  eval {
    print "$attr = " . $config->$attr . "\n";
  };
  if ( $@ ) {
    print STDERR "$attr is not a legal tweakable, or its current value is illegal.\n$@\n";
  };

};