#!/usr/bin/perl

use strict;
use warnings;
use LATMOS::Accounts;
use Getopt::Long;
use Pod::Usage;

=head1 NAME

    la-edit - Tools to edit object in LATMOS::Accounts system

=head1 SYNOPSIS

    la-edit [options] obj_id

=cut

GetOptions(
    'c|config=s' => \my $config,
    'b|base=s'   => \my $base,
    'o|object=s' => \my $otype,
    'e|empty'    => \my $empty_attr,
    'ro'         => \my $with_ro,
    'f=s'        => \my $inputfile,
    'help'       => sub { pod2usage(0) },
) or pod2usage();

$otype ||= 'user';

=head1 OPTIONS

=over 4

=item -c|--config configdir

Use this configuration directory instead of the default one.

=item -b|--base basename

Query this specific base instead of the default one.

=item -o|object object_type

Query will be performed on this object. Default is the 'User' object.

=item -e|--empty

Include also unset attributes

=item --ro

Include also read-only attributes as comment

=item -f FILE

Use this file to get attributes (- use stdin)
If this option is not present, you'll have a file opened in your prefered editor to edit.

=back

=cut

if (!$ARGV[0]) {warn "You must specify 'obj_id', aborting\n"; pod2usage(); }

my $LA = LATMOS::Accounts->new($config, noacl => 1);
my $labase = $LA->base($base);
$labase && $labase->load or die "Cannot load base";
$labase->wexported(1);

sub input_from_handle {
    my ($obj, $fh) = @_;
    my %attr = LATMOS::Accounts::Utils::parse_obj_file($fh);
    my $res = $obj->set_c_fields(%attr);
    if($res) {
        print "Changes applied\n";
        $labase->commit;
        $LA->call_batch_sync;
    }
    return
    $res ? 1 : 0;
}

if (my $ouid = shift(@ARGV)) {
    my $obj = $labase->get_object($otype, $ouid) or do {
        die "Object $otype $ouid not found\n";
    };

    if ($inputfile) {
        my $handle;
        if ($inputfile eq '-') {
            $handle = *STDIN;
        } else {
            open($handle, '<', $inputfile) or die
                "Cannot open input file $@\n";
        }
        my $res = input_from_handle($obj, $handle);
        close($handle);
        exit(!$res);
    } else {
        exit ! LATMOS::Accounts::Utils::dump_read_temp_file(
            sub {
                my ($fh) = @_;
                $obj->text_dump($fh,
                    {
                        empty_attr => $empty_attr,
                        only_rw => !$with_ro,
                    }
                );
            },
            sub {
                my ($fh) = @_;
                return input_from_handle($obj, $fh);
            }
        );
    }
} else {
    pod2usage();
}
