#!/usr/bin/env python3

import socket
import sys
import os
import struct

sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sockpath = "/var/tmp/%s/sexiibot.sock" % os.environ["USER"]

logo = """\
  .-.
 (/ \)
 (\ /)       SEXIIBOT  :  The  Bot  Of  Your  Dreams
 .-'-.             Simple  EXtensible  II  Bot
/(_Y_)\\                     v.0.1.1
\\\\) (//
 /   \                  Author: raspbeguy
 \ Y /              raspbeguy@hashtagueule.fr
  \|/
  /|\     https://git.hashtagueule.fr/raspbeguy/sexiibot
  \|/
  /Y\\
"""

usage = """\
usage: %s [-p <path_to_socket>] <command>

To get a list of possible commands, use command "help"
"""

args = sys.argv

def send_msg(connexion, msg):
    # Prefix each message with a 4-byte length (network byte order)
    msg = struct.pack('>I', len(msg)) + msg
    connexion.sendall(msg)

def recv_msg(connection):
    # Read message length and unpack it into an integer
    raw_msglen = recvall(connection, 4)
    if not raw_msglen:
        return b''
    msglen = struct.unpack('>I', raw_msglen)[0]
    # Read the message data
    return recvall(connection, msglen)

def recvall(connection,n):
    # Helper function to recv n bytes or return None if EOF is hit
    data = b''
    while len(data) < n:
        packet = connection.recv(n - len(data))
        if not packet:
            return b''
        data += packet
    return data

if len(args) < 2:
    print(usage, file=sys.stderr)
    sys.exit(1)
elif args[1] == "-v":
    print(logo)
    sys.exit(0)
elif args[1] == "-p":
    try:
        sockpath = args[2]
    except IndexError:
        print(usage, file=sys.stderr)
        sys.exit(1)
    message = " ".join(args[3:])
else:
    message = " ".join(args[1:])

try:
    sock.connect(sockpath)
except socket.error:
    error = """\
It seems that sexiibot isn't awaken.
To start your sexiibot instance, run the following command:
    sexiictl start <config_file>

It is also possible than the instance of sexiibot you're trying to reach uses a different control socket.
You can try running the following command :
    sexiictl -p <path_to_socket> """ + "".join(sys.argv[1:]) + """

If you need help to generate a config file, use the sexiiwizard script.
"""
    print(error, file=sys.stderr)
    sys.exit(1)
try:
    send_msg(sock, bytes(message, 'UTF-8'))
    response = recv_msg(sock).decode('UTF-8')
    print(response)
finally:
    sock.close()