#!/usr/bin/perl

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

=head1 NAME

    la-sql-properties - Tools to edit object internals SQL base properties

=head1 SYNOPSIS

    la-sql-properties [options] obj_id

=cut

GetOptions(
    'c|config=s' => \my $config,
    'b|base=s'   => \my $base,
    'o|object=s' => \my $otype,
    'nodelete=s' => \my $nodelete,
    '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 --nodelete on|off

Turn attribute C<nodelete> to C<on> or C<off>

=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);

my $ouid = shift(@ARGV) or do { pod2usage(1); };

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

sub checkonoff {
    my ($value, $step) = @_;
    if (! $value =~ /^(on|off)$/) {
        warn "Value for --$step must be on or off\n";
        pod2usage(1);
    }
    return $value eq 'on' ? 1 : 0;
}

if (defined($nodelete)) {
    my $v = checkonoff($nodelete, 'nodelete');
    $obj->SetNoDelete($v);
}

print 'internal: ' . ($obj->get_field('internobject') ? 'yes' : 'no') . "\n";
print 'nodelete: ' . ($obj->get_field('nodelete') ? 'yes' : 'no') . "\n";
