<?php
include_once 'functions.php';

$AWS_ACCESS_KEY_ID=$awsConfig['credentials']['key'];
$AWS_SECRET_ACCESS_KEY=$awsConfig['credentials']['secret'];
$S3_ENDPOINT_URL=$awsConfig['endpoint'];

$hostname = gethostname();

$file = $_SERVER['REDIRECT_URL'];
//$file="/20240827/66cd9ca29a76080bb2705338/8c543c4f-5af7-4000-b723-ff985960dffe/c7205c59e871db435b816a3ecf5c1c71_0";
//$file="/20240825/66ca9e381766f5a895a88d25/a21ce19e-8084-4190-bf27-64fa9d6a586c/8e5ae56ed02930b09b2f20aa0f53c870_0";

$s3_bucket = $awsConfig['bucket'];
$s3_prefix = "/storage";
$s3_full_path = "s3://" . $s3_bucket . '/' . $hostname . $s3_prefix;
$ext = pathinfo($file, PATHINFO_EXTENSION);
if ($ext === 'jpeg') {
        $escaped_file = escapeshellarg($file);
        $s3_path = $s3_full_path . $escaped_file;
        header('Content-Type: image/jpeg');
        $command = "AWS_ACCESS_KEY_ID={$AWS_ACCESS_KEY_ID} AWS_SECRET_ACCESS_KEY={$AWS_SECRET_ACCESS_KEY} S3_ENDPOINT_URL={$S3_ENDPOINT_URL} s5cmd cat $s3_path";

} else {
        $file = $file.'.gz';
        $escaped_file = escapeshellarg($file);
        $s3_path = $s3_full_path . $escaped_file;

        $command = "AWS_ACCESS_KEY_ID={$AWS_ACCESS_KEY_ID} AWS_SECRET_ACCESS_KEY={$AWS_SECRET_ACCESS_KEY} S3_ENDPOINT_URL={$S3_ENDPOINT_URL} s5cmd cat $s3_path | gunzip";
}

// Check if file exists locally
if (file_exists("./$file")) {
        $fp = gzopen("./$file", "r");
        while (!gzeof($fp)) {
                echo gzread($fp, 4096);
        }
        gzclose($fp);
} else {
        // Try to get file from tar archive first
        $fileDetails = getFileDetails($file);
        
        if ($fileDetails !== false) {
                // File exists in tar index
                $tarFilename = $fileDetails['tarFile'];
                $offset = $fileDetails['offset'];
                $filesize = $fileDetails['size'];
                
                if ($fileDetails['isLocal']) {
                    // Read from local tar file
                    $data = fetchLocalByteRange($tarFilename, $offset, $filesize);
                } else {
                    // Read from S3
                    $s3Filename = "{$hostname}/{$tarFilename}";
                    $data = fetchS3ByteRange($s3Filename, $offset, $filesize);
                }
                
                if ($data !== false) {
                    processAndDisplayData($data);
                } else {
                    header("HTTP/1.0 404 Not Found");
                    echo "Error reading file";
                }
        } else {
                // Fall back to original s5cmd method
                $output = shell_exec($command);
                if ($output === null) {
                        header("HTTP/1.0 404 Not Found");
                        echo "File does not exist";
                } else {
                        echo $output;
                }
        }
}
