#!/usr/bin/perl

# Copyright © 2015 SUSE LLC
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, see <http://www.gnu.org/licenses/>.

=head1 modify_needle

modify_needle - manipulate needle (tags) on command line

=head1 SYNOPSIS

modify_needle [OPTIONS] FILE.json [FILEs...]

You can pass multiple files to e.g. 

modify_needle --add-tags COOLTHING *the-cool-needle*.json

=head1 OPTIONS

=over 4

=item B<--add-tags>

check the needle and add the given tags (comma separated) if not yet present

=item B<--help, -h>

print help

=cut

use strict;
use warnings;

use Mojo::JSON;    # booleans
use Cpanel::JSON::XS ();
use Getopt::Long;

sub usage($) {
    my $r = shift;
    eval "use Pod::Usage; pod2usage($r);";
    if ($@) {
        die "cannot display help, install perl(Pod::Usage)\n";
    }
}

my %options;
GetOptions(\%options, "add-tags=s", "help|h",) or usage(1);

usage(0) if $options{help};

my @add_tags = split(q{,}, $options{'add-tags'});

for my $needle (@ARGV) {

    local $/;
    open(my $fh, '<', $needle) || die "can't open $needle";
    my $info = Cpanel::JSON::XS->new->relaxed->decode(<$fh>);
    close $fh;

    my $changed = 0;
    my %tags    = map { $_ => 1 } @{$info->{tags}};
    for my $at (@add_tags) {
        $changed = 1 unless $tags{$at};
        $tags{$at} = 1;
    }
    $info->{tags} = [sort keys %tags];
    next unless $changed;

    open($fh, '>', $needle) || die "can't open $needle";
    print $fh Cpanel::JSON::XS->new->pretty->encode($info);
    close $fh;
}
