#!/usr/bin/perl

use DBI;
use strict;
use POSIX;
#use ESL;
use Switch;
use Time::HiRes;
use WWW::Curl::Easy;
use JSON;
use Config::Tiny;
use Data::Dumper;
use Cwd;
use URI;
use threads;
use Thread::Semaphore;
use threads::shared;
use POSIX qw(strftime);
use Dinstar;
use CGI qw/:standard/;
#use HTTP::Cookies;
#use LWP::UserAgent;

   my $jsessionid = loginDinstar();
   SlotChange();

   # -------------------------------------------------------
   # Cambio Puerto por que no esta entregando mas Mensajes
   # -------------------------------------------------------

   sub SlotChange {
#     my $jsessionid = "04da2cf43ee22cdf6f3fb49708b2daf97e";
#     my $jsessionid = "084addb3f5ad32aad4f2607392e3a56585";
      my $auth = "admin:pepito20";
      my $ip = "10.0.66.104";
      my $port = 12;
      my $slot = "A";

      my $rc = disableSlot( $ip, $port, $slot, $auth, $jsessionid,"db49-c230-9183-0071");
      printf( "rc = %d\n", $rc );
      $rc = enableSlot( $ip, $port, "C", $auth, $jsessionid,"db49-c230-9183-0071" );
      printf( "rc = %d\n", $rc );
#     PortChangeStatus( $conn, $gw, $port );
   }


   # -----------------------------------
   # loginDinstar
   # -----------------------------------

   sub loginDinstar {
      my $ip = "10.0.66.104";
      my $name = "admin";
      my $password = "pepito20";
      my $jsessionid = "";
     	my $app_folder = getcwd;

      my $url = "$ip/goform/IADIdentityAuth";
      my $content = "username=$name&password=$password";
		my $cookiefile = $app_folder . "/cookies.txt";

      my $curl = WWW::Curl::Easy->new;
      $curl->setopt( CURLOPT_HEADER,0);
      $curl->setopt( CURLOPT_URL, $url);
      $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
      $curl->setopt( CURLOPT_POSTFIELDS, $content );
      $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
      $curl->setopt( CURLOPT_POST, 1);
      $curl->setopt( CURLOPT_TIMEOUT, 0);
      $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
      $curl->setopt( CURLINFO_HEADER_OUT, 1 );
      $curl->setopt( CURLOPT_COOKIEJAR, $cookiefile );

      my $response_body;
      $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
      my $retcode = $curl->perform;
      my $error_text = "";

#      /JSESSIONID([^;]+)
      if ($retcode == 0) {
	   	my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	   if( $response_code == 200 ) {

            my $string;
            my $index;

            open(my $fh, '<', $cookiefile);
            while (my $line = <$fh>) {  # Read one line at a time
                chomp $line;  # Remove trailing newline
                if(  ( $index = index( $line, 'JSESSIONID') ) > 0 ) {
                  $string =  substr($line,$index);
                  $string =~ s/\s+//g;
                  $jsessionid =  substr( $string, 10 );
                  last;
               }
            }
            close $fh;
            return $jsessionid;
        	}
      }
      return "";
   }



