#!/usr/bin/perl

## no critic (Modules::RequireNoMatchVarsWithUseEnglish);
## no critic (InputOutput::RequireBracedFileHandleWithPrint);
## no critic (CodeLayout::ProhibitParensWithBuiltins);

# Set the "when_created" field for an account.

use strict;
use warnings;
use autodie;

use CGI ;
use English ;
use Try::Tiny;

use Stanford::Schema::WebApps::SharedEmail ;
use Stanford::WebApps::SharedEmail::Config qw(%CONFIG) ;

my $VERBOSE = 1 ;

##################################################################
sub progress {
    my ($msg) = @_ ;
    if ($VERBOSE) {
	print "progress: $msg\n" ;
    }
    return ;
}

sub exit_with_error {
    my ($msg) = @_ ;
    my $q = CGI->new ;
    print $q->header(
        -type  => 'text/plain',
        -status=> '500 Processing Error'
        );
    print $msg ;
    print "\n" ;

    exit(1) ;
}

sub exit_with_success {
    my ($msg) = @_ ;
    my $q = CGI->new ;
    print $q->header(
        -type   => 'text/plain',
        -status => '200 Success'
        );
    print $msg ;
    print "\n" ;

    exit(0) ;
}

sub get_account_name {
    my $q = CGI->new ;

    # Get the name of the account to set.
    return $q->param('account');
}

sub db_connect {
    my $dbh = Stanford::Schema::WebApps::SharedEmail->connect(\%CONFIG) ;
    if (!$dbh) {
        exit_with_error('error connecting to database: ' . $ERRNO) ;
    } else {
        progress('successfully made connection to database') ;
    }

    return $dbh ;
}

sub get_account_record {
    my ($dbh, $account) = @_ ;

    my $target = $dbh->resultset('Account')->search({
        account => $account,
    }, {
        for => 'update',
    });

    if ($target->count == 0) {
        my $msg = "no account with name '$account' found" ;
        exit_with_error($msg);
    }

    return $target->first ;
}

sub update_record {
    my ($target) = @_ ;

    my $now_scalar = 'NOW()';
    $target->when_created(\$now_scalar);
    $target->update;

    return ;
}

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

my $msg ;

# Make connection to the shared email database.
my $dbh = db_connect() ;

# Get the name of the account to set.
my $acct_to_set = get_account_name() ;

if (!$acct_to_set) {
    $msg = q{no POST'ed account} ;
    exit_with_error($msg) ;
} else {
    progress("found account $acct_to_set") ;
}

# Get the record with the given account name.
my $account_rec = get_account_record($dbh, $acct_to_set) ;

# Update the record.
try {
    update_record($account_rec) ;
} catch {
    $msg = "error updating record '$acct_to_set': $_" ;
    exit_with_error($msg) ;
};

$msg = "Just updated $acct_to_set" ;
exit_with_success($msg) ;
