#!/usr/bin/env python
#
# $VER: netclip.py 0.2 (23.1.2013) by Patrik Axelsson 2013
#
# A simple cross-platform client for http://aminet.net/package/comm/tcp/netclip
#

import sys
import struct
import socket

if 3 != len(sys.argv):
	sys.exit("Usage: " + sys.argv[0] + " hostname clipString")

hostname = sys.argv[1]
clipString = sys.argv[2]
	
s = socket.socket()
netclipPort = 2971
try:
	s.connect((hostname, netclipPort))
except Exception, e:
	sys.exit("Problem connecting to '" + hostname + "': " + e.strerror)

innerIFFPart = "FTXT" + "CHRS" + struct.pack(">i", len(clipString)) + clipString
# If the data isn't an even number of Bytes, netclipd refuses to read it.
if 0 != len(innerIFFPart) % 2:
	innerIFFPart += "\x00"
completeIFF = "FORM" + struct.pack(">i", len(innerIFFPart)) + innerIFFPart

dataLength = struct.pack(">i", len(completeIFF))
s.send(dataLength)
handshake = s.recv(len(dataLength))

# Normally netclipd sends dataLength back as an handshake. I assume it will
# send something else back if something went wrong, like not memory at other
# end, so will not send any data in that case.
if dataLength == handshake:
	s.send(completeIFF)
s.close()
