#!/usr/bin/env python
#
# $VER: netclipd.py 0.2 (28.9.2015) by Patrik Axelsson 2015
#
# A simple cross-platform inetd style server for http://aminet.net/package/comm/tcp/netclip
#
# To use it add this line to your services file:
# netclip	2971/tcp
#
# And something like the following line to your inetd configuration file (args part in below example is for linux):
# netclip		stream	tcp	nowait	youruser	/path/to/netclipd.py	netclipd.py "xsel -i --display :0.0"
#

import sys
import struct
import subprocess
import shlex

if 2 != len(sys.argv):
	sys.exit("Usage: " + argv[0].rsplit("/")[-1] + " commandToPipeClipboardTextInto")

dataSize = struct.unpack(">i", sys.stdin.read(4))[0]
# Send OK handshake to client
sys.stdout.write(struct.pack(">i", dataSize))
sys.stdout.flush()

if not "FORM" == sys.stdin.read(4):
	sys.exit("Not an IFF FORM")

formPayloadSize = struct.unpack(">i", sys.stdin.read(4))[0]

if not "FTXTCHRS" == sys.stdin.read(8):
	sys.exit("Does not contain an FTXT chunk")

chunkPayloadSize = struct.unpack(">i", sys.stdin.read(4))[0]

# Does not care about the payload size, just reads the data available which
# should be a string with length chunkPayloadSize Bytes or formPayloadSize - 12
process = subprocess.Popen(shlex.split(sys.argv[1]), stdin=subprocess.PIPE)
process.communicate(sys.stdin.read())
returnCode = process.wait()
