#!/opt/alt/python38/bin/python3
#
# Wait for PAM socket is ready
#
from configparser import ConfigParser
import socket as s
import sys
import time

CONFIG = '/etc/pam_imunify/i360.ini'
PAMSOCK_PATH = '/opt/i360_pam_imunify/pam_imunify360.sock'
DELAY = 1
TIMEOUT_DEFAULT = 120

try:
    _log = open('/var/log/imunify360/pam.log', 'a', buffering=1)
except OSError:
    _log = open('/dev/null', 'a')


def _print(msg, level='debug'):
    print(msg, file=sys.stderr)
    print('time="%s"' % time.strftime('%Y-%m-%dT%H:%M:%S%Z'),
          "level=%s" % level,
          'msg="%s"' % msg,
          file=_log)


def pam_imunify_config():
    try:
        with open(CONFIG) as f:
            conf = ConfigParser(default_section='-')
            conf.read_string("[-]\n" + f.read())
            return conf['-']
    except Exception as e:
        # being robust!
        _print("%s parsing error: %s" % (CONFIG, e), level='error')
        return {}


if __name__ == '__main__':
    pamsock = s.socket(s.AF_UNIX, s.SOCK_STREAM)
    t0 = time.time()
    try:
        timeout = float(pam_imunify_config()['socket_readycheck_timeout'])
    except KeyError:
        timeout = TIMEOUT_DEFAULT
    except ValueError as e:
        timeout = TIMEOUT_DEFAULT
        _print("%s 'socket_readycheck_timeout=...' key parsing error: %s" % (CONFIG, e), level='error')

    while True:
        try:
            pamsock.connect(PAMSOCK_PATH)
        except (ConnectionRefusedError, FileNotFoundError) as e:
            _print("PAM socket error: %s" % e)
            if time.time() >= t0 + timeout:
                break
            time.sleep(DELAY)
        else:
            _print("PAM socket is ready.")
            sys.exit(0)
    _print("Failed to connect PAM socket in time.", level='error')
    sys.exit(1)
