#!/usr/bin/python

################################################################################
# Copyright (c) 2004-2005 Christoph Wegscheider <cw@wegi.net>                  #
#                                                                              #
# Permission is hereby granted, free of charge, to any person obtaining a copy #
# of this software and associated documentation files (the "Software"), to     #
# deal in the Software without restriction, including without limitation the   #
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or  #
# sell copies of the Software, and to permit persons to whom the Software is   #
# furnished to do so, subject to the following conditions:                     #
#                                                                              #
# The above copyright notice and this permission notice shall be included in   #
# all copies or substantial portions of the Software.                          #
#                                                                              #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR   #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,     #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE  #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER       #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING      #
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS #
# IN THE SOFTWARE.                                                             #
################################################################################


import sys
import os
import ixplib



version = """pywmir - python window manager improved remote - version 1-current
(C)opyright 2004-2005 Christoph Wegscheider"""



help = """usage: pywmir -v
       pywmir [-s <socket file>] <action [params]>
       pywmir [-s <socket file>] -f
       options:
               -s socket file, defaults to $WMIR_SOCKET
               -f read actions from stdin
               -v show version info
               -h show this help
       actions:
               write  file [string]        -- write a string to a file
               read   path/file            -- read file or directory contents
               remove path/file            -- remove file or directory tree
               create path/file [string]   -- create a file and optionally write a string to it"""



def perform(client, argv):
	if argv[0] == 'read':
		fd = client.open(argv[1])
		print client.read(fd)
		client.close(fd)
	elif argv[0] == 'write':
		fd = client.open(argv[1])
		if sys.stdin.isatty():
			if len(argv) > 2:
				client.write(fd, argv[2])
			else:
				client.write(fd)
		else:
			client.write(fd, sys.stdin.read().strip('\n'))
		client.close(fd)
	elif argv[0] == 'remove':
		client.remove(argv[1])
	elif argv[0] == 'create':
		client.create(argv[1])
		if len(argv)>2:
			fd = client.open(argv[1])
			client.write(fd, argv[2])
			client.close(fd)



def parse_argv(argv):
	#  help
	if len(argv) == 0 or argv[0] == '-h':
		print version
		print '\n', help
		return 0

	# version
	if argv[0] == '-v':
		print version
		return 0

	# sockfile
	if argv[0] == '-s':
		sockfile = argv[1]
		argv = argv[2:]
	elif os.environ['WMIR_SOCKET']:
		sockfile = os.environ['WMIR_SOCKET']
	else:
		print "no socket file given"
		sys.exit(1)

	# read commands from stdin?
	read_stdin = False
	if argv[0] == '-f':
		read_stdin = True
		argv = argv[1:]

	# exec action
	client = ixplib.Client(sockfile)
	if read_stdin:
		while 1:
			s = sys.stdin.readline()
			if s == '':
				break
			perform(client, s.lstrip().rstrip().split())
	else:
		perform(client, argv)
	return 0



if __name__ == '__main__':
	sys.exit(parse_argv(sys.argv[1:]))
