#!/usr/bin/perl

use strict;
use DBI;
use Getopt::Long;
use Pod::Usage;
use Time::Local;
use Rings::Common;

my $opt_conf;
my $opt_debug;
my $opt_help;
my $opt_manual;

##############################################################################
# Main Routine
##############################################################################

print ">>> ring-set-new   v:30-Oct-2016\n";

# -- get options
GetOptions(
    'debug'  => \$opt_debug,
    'help'   => \$opt_help,
    'manual' => \$opt_manual
);

# -- help the poor souls out
if (!@ARGV || $ARGV[0] == 'help') {
    $opt_help = 1;
}
if ($opt_help) {
    pod2usage(-verbose => 0);
}
if ($opt_manual) {
    pod2usage(-verbose => 2);
}

# Set the picture range to process from the command line
my $pid_start = $ARGV[0];
if ($pid_start < 1) {
    pod2usage(-verbose => 0);
}
my $pid_end = $pid_start;
if ($ARGV[1]) {
    $pid_end = $ARGV[1];
}

# Get configuration settings and initial debugging if requested.
get_config($opt_conf);
if ($opt_debug) {
    $CONF->debug($opt_debug);
}
if ($CONF->debug) {
    dbg("Initialize timer.");
}

# Open up connections to the MySQL data
db_connect();

my $sel = "SELECT i.pid pid ";
$sel .= "FROM pictures_information i ";
$sel .= "LEFT OUTER JOIN picture_rings d ";
$sel .= "ON (i.pid = d.pid) ";
$sel .= "WHERE d.pid IS NULL ";
my $sth = $DBH->prepare($sel);
if ($opt_debug) {
    dbg($sel);
}
$sth->execute();
if ($sth->err) {
    sql_die($sel, $sth->err, $sth->errstr);
}

my @pidList;
while (my $row = $sth->fetchrow_hashref) {
    push @pidList, $row->{pid};
}

my $cmd = "INSERT INTO picture_rings ";
$cmd .= "(uid, pid) VALUES (?, ?) ";
if ($opt_debug) {
    dbg($cmd);
}
my $sth_update = $DBH_UPDATE->prepare($cmd);

foreach my $i (@pidList) {
    $sth_update->execute('new', $i);
    if ($sth->err) {
        sql_die($cmd, $sth_update->err, $sth_update->errstr);
    }
}

exit;

__END__

=head1 NAME

ring-set-new - set the uid to new for unlinked pictures

=head1 SYNOPSIS

ring-set-new [--conf=<configuration file>][--debug] [--help] [--manual]


=head1 DESCRIPTION

Add UID of new to any picture that does not have at least one UID.

=head1 OPTIONS AND ARGUMENTS

=over 4

=item --conf=<configuration file>

The name a Rings configuration file.

=item --help

Displays help text.

=item --manual

Displays more complete help text.

=item --debug

Turns on debugging displays.

=back

=head1 AUTHOR

Bill MacAllister <bill@ca-zephyr.org>

=cut
