#!/usr/bin/perl

BEGIN { use lib '/usr/home/cfg' ; require push_inc ; }
    
require cfg ;

&today ;

#------------------------------------------------------------------------------------------

@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'});

foreach $ARG (@ARGV) { ($par,$val) = split(/\=/,$ARG) ; $param{$par} = $val ; }
	
# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/correct_linked_vpu_id.pl?1

our $debug    = $ARGV[0] ;
our $username = 'rory' ;

# print "\n debug : $debug \n" ; 

if ($debug) { print "Content-type: text/html\n\n"; }

&common_debug("\n 1. START") ; 

#------------------------------------------------------------------------------------------

&today ;
&common_debug("\n 2. START") ; 
# &set_delete_date ;
&read_sessions ;

if ($debug) { print "Done."; }

exit;


#------------------------------------------------------------------------------------------

sub read_sessions {

&db_open_ro ;

# my $sql = qq(
# SELECT id,c2.id2 FROM `cameras` c1
# LEFT JOIN (
	# SELECT id AS 'id2',substr(camera_nr,4,7) AS 'sub_cam_nr', camera_nr AS 'camera_nr_2' FROM `cameras` WHERE camera_nr LIKE 'vpu%' AND (camera_nr LIKE '%s1%' OR camera_nr LIKE '%s2%') 
# ) c2 ON c2.sub_cam_nr = c1.camera_nr
# WHERE c1.camera_nr NOT LIKE 'vpu%' AND (c1.camera_nr LIKE '%s1%' OR c1.camera_nr LIKE '%s2%') AND linked_vpu_id = 0
# ) ;

my $sql = qq~
SELECT c2.id,c1.id FROM `cameras` c1
left join (
    SELECT id,camera_nr,event_linked_vpu FROM `cameras` WHERE camera_nr NOT LIKE 'vpu%' AND (camera_nr LIKE '%s1%' OR camera_nr LIKE '%s2%') 
) c2 on c2.event_linked_vpu = c1.serial_nr
WHERE c1.camera_nr LIKE 'vpu%' AND (c1.camera_nr LIKE '%s1%' OR c1.camera_nr LIKE '%s2%') and linked_vpu_id = 0 and c2.id is not null ;
~ ;

&common_debug("\n 3 . START "); 

my $sth = $dbh->prepare($sql) ;

$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!";
$id_array_ref = $sth->fetchall_arrayref();
$sth->finish();
# my $cnt = 0 ; 

foreach my $row (@$id_array_ref) {
	next unless @$row[1] ;
	# last if $cnt ; 
	# $cnt++ ; 
	# &common_debug("\n UPDATE cameras SET linked_vpu_id = @$row[1] WHERE id = @$row[0] \n") ; 
	$sql = qq~UPDATE cameras SET linked_vpu_id = @$row[1] WHERE id = @$row[0] ; ~ ;
	&common_debug("$sql") ; 
	$sth = $dbh -> do ($sql) or die "could not execute :<BR>$sql<BR>$!" ;
	
    # foreach (@a_session) {
        # my ($param,$val) = split(/=>/) ;
        # if ($param =~ /timestamp/) {
            # my $date_ccyy_mm_dd = substr($val,2,10);
            # my ($sccyy,$smm,$sdd) = split(/\-/,$date_ccyy_mm_dd);
            # my $sdate = $sccyy . $smm . $sdd ;
            # if ($sdate < $delete_date) {
                # print "<br>($sdate < $delete_date)" ;
                # # &delete_session($id) ;
                # }
            # }
        # }
}
	
&db_close_conn ;

} #-------------------------------------------------------------------------------

use db ;
use today ;
use common ;
use common_min ;
