#!/usr/bin/env python

# This file is part of Window-Switch.
# Copyright (c) 2009-2013 Antoine Martin <antoine@nagafix.co.uk>
# Window-Switch is released under the terms of the GNU GPL v3

import socket
import os.path

from winswitch.util.simple_logger import Logger
logger=Logger("unix_socket_util", log_colour=Logger.MAGENTA)


def unix_socket_send(socket_path, message):
	if not os.path.exists(socket_path):
		logger.serror("socket path does not exist", socket_path, message)
		return
	import errno
	import select
	sock = socket.socket(socket.AF_UNIX)
	sock.settimeout(5)
	try:
		logger.slog("sending", socket_path, message)
		sock.connect(socket_path)
		written = 0
		while written < len(message):
			select.select([], [sock], [])
			written += sock.send(message[written:])
		logger.slog("sent", socket_path, message)
		sock.close()
	except socket.error, e:
		logger.serror("error: %s" % e, socket_path, message)
		err = e.args[0]
		if err in (errno.ECONNREFUSED, errno.ENOENT):
			logger.serror("connection refused!", socket_path, message)
