#!/usr/bin/perl

## no critic (Modules::RequireNoMatchVarsWithUseEnglish);

# Link any workgroups that still need linking for shared-email accounts.

use strict ;
use warnings ;
use autodie ;

use Carp ;
use DBI ;
use English ;
use File::Temp ;

use Stanford::Schema::WebApps::SharedEmail ;
use Stanford::WebApps::SharedEmail::Config qw(%CONFIG) ;
use Stanford::WebApps::SharedEmail::Util qw(
    remctl_link_workgroup
    refresh_krb5_cache
    link_workgroup_enabled
) ;

# ### ## ### ## ### ## ### ## ### ## ### ## ### ## ### ## ### ## ### #
sub log_error {
    my ($msg) = @_ ;
    print {*STDERR} $msg . "\n" ;
    return ;
}

my $VERBOSE = 1 ;

sub progress {
    my ($msg) = @_ ;

    if ($VERBOSE) {
        print "progress: $msg\n" ;
    }
    return ;
}

# ### ## ### ## ### ## ### ## ### ## ### ## ### ## ### ## ### ## ### #

use Data::Dumper ;

progress('starting run of shared-email-link');

# This script only proceeds if workgroup linkage is enabled.
if (!link_workgroup_enabled()) {
    progress('workgroup linkage not enabled; exiting shared-email-link');
    exit 0;
} else {
    progress('workgroup linkage is enabled; continuing with shared-email-link');
}

# Make connection to the shared email database.
my $dbh = Stanford::Schema::WebApps::SharedEmail->connect(\%CONFIG) ;
if (!$dbh) {
    croak 'error connecting to database: ' . $ERRNO ;
} else {
    progress('successfully made connection to database') ;
}

##<<< perltidy: this is how I like it
#my $query = 'SELECT account FROM account ' .
#            'WHERE (is_approved = 1) AND ' .
#                  '(when_moved IS NULL) AND ' .
#                  '(when_created IS NULL)';
##>>>

my $resultset = $dbh->resultset('Account')->search({
    is_approved  => 1,
    when_moved   => undef,
    when_created => undef,
                                                       });
my @results = $resultset->all() ;

# List results
my $workgroup_link_server
    = $CONFIG{'workgroup_link_server'} ;
my $workgroup_link_server_principal
    = $CONFIG{'workgroup_link_server_principal'} ;
my $workgroup_link_environment
    = $CONFIG{'workgroup_link_environment'} ;

my $krb5_keytab = $CONFIG{'krb5_keytab'} ;

# Make a temporary file to hold the credentials. (Be sure
# to delete before exiting.) We do NOT use the ccache
# credentials file defined in /etc/shared-email as
# this script might run as root and hence set the
# Kerberos credentials cache to be readable only by root. But
# the same credentials cache is needed by the web application
# that runs as www-data.
my ($fh, $ccache_tmp) = File::Temp::tempfile() ;
close($fh) ;
refresh_krb5_cache($krb5_keytab, $ccache_tmp) ;

my $total_processed = 0 ;
foreach my $result (@results) {
    my $acct_to_link = $result->account ;

    progress("processing '$acct_to_link'") ;
    progress("calling remctl on $workgroup_link_server for workgroup link") ;
    my ($stdout, $stderr, $rc) = remctl_link_workgroup($workgroup_link_server,
                                                       $workgroup_link_server_principal,
                                                       $acct_to_link,
                                                       'jcowart',
                                                       $workgroup_link_environment) ;
    if ($rc != 0) {
        unlink $ccache_tmp ;
        croak "error: $stdout/$stderr" ;
    }

    if ($stdout eq '0') {
        progress("matched $acct_to_link") ;
        my $now_string = 'NOW()' ;
        $result->update({ when_moved => \$now_string });
        progress("updated the $acct_to_link record") ;
    } else {
        chomp $stdout;
        progress("stdout was not '0'") ;
        progress("stdout: $stdout") ;
        progress("stderr: $stderr") ;
    }

    progress("end of processing '$acct_to_link'") ;
    ++$total_processed ;
}

unlink $ccache_tmp ;
progress("finished run of shared-email-link ($total_processed processed)");

exit 0 ;

#####################################################################

__END__

=head1 NAME

share-email-link - Link shared-email accounts in Workgroup Manager

=head1 SYNOPSIS

shared-email-link

=head1 DESCRIPTION

B<shared-email-link> looks for any approved shared-email requests. For any
such requests that have not yet been linked in the Workgroup Linkage
system to a Windows Actice Directory group, a remctl call is made to make
that linkage

=head1 OPTIONS

None.

=head1 EXIT STATUS

Returns C<0> on success, C<1> on any failure.

=head1 LICENSE AND COPYRIGHT

Copyright 2021 The Board of Trustees of the Leland Stanford Junior
University.  All rights reserved.

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted, provided
that the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation, and that the name of Stanford University not be used in
advertising or publicity pertaining to distribution of the software
without specific, written prior permission.  Stanford University makes no
representations about the suitability of this software for any purpose.
It is provided "as is" without express or implied warranty.

THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.

=cut

#####################################################################
