#!/usr/bin/env perl

use IO::Socket;
use File::Spec;

$socket = IO::Socket::INET->new(PeerAddr => "127.0.0.1",
                                PeerPort => 1234,
                                Proto    => "tcp",
                                Type     => SOCK_STREAM);

my $absolute_path = File::Spec->rel2abs($ARGV[0]);

# Send the length of the first argument as four bytes.
$socket->send(pack("L", length($absolute_path)));
# Send the first argument as a string.
$socket->send($absolute_path);

# Get and send the content of the file, prefixed by its length.
my $content = do{local(@ARGV,$/)=$absolute_path;<>};
$socket->send(pack("L", length($content)));
$socket->send($content);

# Get size of written content. This blocks until the players hits save or close.
my $length_str;
$socket->recv($length_str, 4);
my $length = unpack("L", $length_str);
my $new_content = "";
$socket->recv($new_content, $length);

# Write content back into the file.
my $handle;
open ($handle,'>',$absolute_path) or die("Error opening file");
print $handle $new_content;
close ($handle) or die ("Error closing file");

# This call is intended to block, we're waiting for Godot to close the connection.
my $reply;
$socket->read($reply, 1000);
