<?php
if (file_exists("s3upload/aws-module/aws-autoloader.php")) {
    include 's3upload/aws-module/aws-autoloader.php';
}

use Aws\S3\S3Client;
use Aws\Api\Middleware;
use Aws\S3\Exception\S3Exception;

$bucket         = 'fukey-s3-bucket';
$access_key     = 'AKIASSUFC7533X3BTI7X';
$seceret_key    = 'TNHvN8oXmJzd914N2NWNs+oNb/+71KUvKLpd2tuf';
$region         = 'ap-south-1';

if ($argv[1] & $argv[2] & $argv[3]) {

    $roomId = $argv[1];
    $file = $argv[2];
    $agentId = $argv[3];
    $s3config = array(
          'region'  => $region,
          'version' => 'latest',
          'credentials' => [
              'key'    => $access_key,
              'secret' => $seceret_key
          ]
      );

    // Instantiate an Amazon S3 client
    $s3 = new S3Client($s3config);
    //$s3->getHandlerList()->appendSign(Middleware::correctClockSkew(), 'correct_clock_skew');
    // Path to the MP4 file to upload
    $file_path      = 'recordings/' . $file;
    $copy_file_path = 'redord/' . $file;
    copy($file_path, $copy_file_path);  

    // // Compressing of the video file 
    // $low_file_path = 'low_recording/' . $file;
    // $command = "ffmpeg -i $copy_file_path -b:v 500k $low_file_path";
    // exec($command, $output, $return_code);

    // if ($return_code === 0) {
    //     echo 'Bitrate reduction successful!';
    // } else {
    //     echo $return_code;
    // }
    
    // Key name (object name) under which the file will be stored in the S3 bucket
    $key =  $agentId . '/' . $roomId . '/' . $file;
    $success =  true;

    try {
        // Upload the MP4 file to S3
        $result = $s3->putObject([
              'Bucket' => $bucket,
              'Key'    => $key,
              'Body' => fopen($file_path, 'rb')
          ]);

        // Print the URL of the uploaded file
        echo $result['ObjectURL'];
    } catch (S3Exception $e) {
        // Handle S3 upload errors
        $success =  false;
        echo 'S3Error'.$e->getMessage();
    } catch (Exception $e) {
        // Handle other errors
        $success =  false;
        echo 'Error'.$e->getMessage();
    }

    // if(file_exists($copy_file_path) && $success) {
    //     unlink($copy_file_path);
    // } 
    // if(file_exists($file_path) && $success) {
    //     unlink($file_path);
    // } 
}

// echo 'skipped s3 upload';
?>