#!/usr/bin/env perl
#>*******************************************************
# THIS FILE WAS AUTO-GENERATED BY ATLASSIAN BITBUCKET.
# IT CONTAINS NO USER-SERVICEABLE PARTS.
#>*******************************************************
use strict;
use IO::Socket;

sub stream {
    my ($handle) = shift;

    while (read($handle, my $buffer, 8192)) { # Read 8k blocks
        print STDOUT $buffer;
    }
    close($handle);
}

# All output from this script should be treated as binary
binmode(STDOUT);

my $file = $ARGV[0];
my $host = $ENV{"STASH_GIT_TRANSCODE_HOST"};
my $port = $ENV{"STASH_GIT_TRANSCODE_PORT"};
if (defined $host and defined $port) {
    my $socket = IO::Socket::INET->new(
            PeerAddr => $host,
            PeerPort => $port,
            Proto => "tcp");
    die "Could not connect to Stash on $host:$port: $!\n" unless $socket;
    binmode($socket, ":raw");

    # Write the path to transcode to the socket and then shutdown write
    print $socket $file;
    shutdown($socket, 1); # That's all we'll ever write to the socket

    # If the path is invalid or some other type of error happens the server will not write
    # any data; it will just close the socket. The same happens for empty files
    stream($socket);
} else {
    # If the transcode port is not set, just print the file. This ensures running git diff
    # "normally" in the repository works as expected (aside from not transcoding content
    # even when transcoding is enabled)
    open(my $fileHandle, "<", $file) or die "Cannot open $file\n";
    binmode($fileHandle);
    stream($fileHandle);
}