#!/usr/local/bin/python3.8

#   Copyright 2009-2018 Oli Schacher
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


# This tool is used to send messages to the fuglu control port

import sys
import socket
from optparse import OptionParser
from fuglu.localStringEncoding import force_bString, force_uString

def usage():
    return """
    
    Usage fuglu_control <command> [<args>]
    Available commands:
    stats : show statistics
    uptime: show long fuglu has been running
    workerlist: show current status of all mail scanning threads
    threadlist: show current status of ALL threads (core + workers)
    exceptionlist: last 10 exception tracebacks
    netconsole [<port> [<bind address>]] : start a python interactive shell on a network socket
    """

optionparser = OptionParser(usage=usage())
optionparser.add_option("-p", dest="port", action="store",
                        default="/tmp/fuglu_control.sock", help="Unix socket or port to connect to")
(options, pargs) = optionparser.parse_args()


if len(pargs) < 1:
    optionparser.print_usage()
    sys.exit(1)


localport = options.port
iport = None
try:
    iport = int(localport)
except:
    pass

cmd = " ".join(pargs)
# connect to debug port
if iport != None:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
else:
    s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)

try:
    if iport != None:
        s.connect(('127.0.0.1', iport))
    else:
        s.connect(localport)
except Exception as e:
    print("Cannot connect to fuglu control deamon (%s) - is fuglu running?" % localport)
    print(str(e))
    sys.exit(1)

s.sendall(force_bString(cmd))
data = s.recv(32768)
s.close()
print(force_uString(data))
