#!/usr/bin/perl 
#
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (c) Rainer Gümpelein, TeilRad GmbH
#
#set availabel if requested > 15min
#
#Example
#./src/scripts/requested_timeout.pl shareedms-operator
#
#
use vars qw($syshost);

BEGIN {
  $syshost = $ARGV[0] || die;
}

use lib "/var/www/copri-bike/$syshost/src";

use strict;
use warnings;
use POSIX;
use CGI ':standard';
use Lib::Config;
use Mod::DBtank;
use Mod::APIfunc;
use Data::Dumper;

my $q = new CGI;
my $cf = new Config;
my %varenv = $cf->envonline("$syshost");
my $dbt = new DBtank;
my $apif = new APIfunc;
my $now_dt = strftime "%Y-%m-%d %H:%M:%S", localtime;
my $dbh = "";

my $interval_min = "15";
$interval_min = $ARGV[1] if($ARGV[1] && $ARGV[1] =~ /^\d+$/);

#set available if requestes older than 15 minute
my $return={};
my $pref = {
        table           => "contenttranspos",
        fetch           => "all",
        keyfield        => "c_id",
	int10		=> "2",
        start_time      => "<=::(now() - interval '$interval_min minutes')",
};
my $record_cp = $dbt->fetch_tablerecord($dbh,$pref);

my $update_cp = {
        table   =>	"contenttranspos",
        int10   =>      "1",
	owner_end => "172",
	mtime => "now()",
};
my $update_cc = {
        table   =>	"content",
        int10   =>      "1",
};

my $rows = 0;
foreach my $id (sort { $record_cp->{$a}->{c_id} <=> $record_cp->{$b}->{c_id} } keys (%$record_cp)){
	#contenttranspos
	my $record_cpone = { c_id => 0 };
	$record_cpone->{c_id} = $record_cp->{$id}->{c_id};
	$update_cp->{int04} = $record_cp->{$id}->{int06};#set end-station to start-station 
	$rows = $dbt->update_record($dbh,$update_cp,$record_cpone);

	if($rows > 0 && $record_cp->{$id}->{cc_id}){
	  #content
	  my $record = { c_id => 0 };
	  $record->{c_id} = $record_cp->{$id}->{cc_id};
	  $dbt->update_record($dbh,$update_cc,$record);
	  my $authraw = { c_id => 0 };
	  $apif->stations_caching($q,\%varenv,$authraw);
  	}
}

1;
