#!/usr/bin/env python

from __future__ import print_function

"""
A control agent for SignServer
        
"""

"""
RCSid:
	$Id: signctl.py,v 1.16 2023/05/19 06:38:07 sjg Exp $

	@(#) Copyright (c) 2012-2022 Simon J. Gerraty

	This file is provided in the hope that it will
	be of use.  There is absolutely NO WARRANTY.
	Permission to copy, redistribute or otherwise
	use this file is hereby granted provided that 
	the above copyright notice and this notice are
	left intact. 
      
	Please send copies of changes and bug-fixes to:
	sjg@crufty.net

"""

import sys
import socket
import time
import errno
from sign import *
from p3compat import *

def sendctl(url, cmd):
    sock_family,connect_to = url2sock_address(url)
    sock,msg = urlconnect([(sock_family,socket.SOCK_STREAM,0,'',connect_to)], tries)
    if not sock:
        sys.stderr.write(msg+'\n')
        if msg.find(str(errno.ECONNREFUSED)+':') > 0:
            sys.exit(os.EX_UNAVAILABLE)
        sys.exit(1)

    rc = False
    sock.send(b('signctl: {0}\n'.format(cmd)))
    while True:
        try:
            msg = sock.recv(1024)
        except:
            msg = None
        if not msg or msg.startswith(b'ERROR'):
            break
        if msg.startswith(b(cmd)):
            rc = True
            break
        
    if msg:
        if msg.startswith(b'ERROR'):
            sys.stderr.write(msg+'\n')
            sys.exit(1)
        print(msg, end='')
    sock.close()
    return rc
    
if __name__ == '__main__':
    import getopt

    conf = initConfig(None)
    if '.Vars' in conf:
        conf = loadConfig('${progdir}/${progname:R}.cf', conf, False)
        conf = loadConfig('./${progname:R}.cf', conf, False)
    else:
        Myname = basename(sys.argv[0], '.py')
        Mydir = os.path.dirname(sys.argv[0])
        myconf = Myname + '.cf'
        for d in [Mydir, '.']:
            cf = d + '/' + myconf
            if os.path.exists(cf):
                conf = loadConfig(cf, conf)

    opts,args = getopt.getopt(sys.argv[1:], 'dc:r:u:')
    for o,a in opts:
        if o == '-c':
            conf = loadConfig(a, conf)
        elif o == '-d':
            conf['debug'] = int(conf.get('debug', 0)) + 1
        elif o == '-r':
            conf['tries'] = a
        elif o == '-u':
            conf['url'] = a

    tries = int(conf.get('tries', 2))
    port = conf.get('ListenPort', 6161)
    url = conf.get('url', 'localhost:{}'.format(port))

    for cmd in args:
        sendctl(url, cmd)
        if cmd == 'shutdown':
            i = 128
            while i > 0:                 # loop until we fail
                sendctl(url, cmd)
                time.sleep(1)
                i -= 1

    sys.exit(0)
