#!/usr/bin/python3
"""The test project's Vault seen from an instance, which logs in with its own AppRole: lm-dev-vault init|get|totp.

lm-dev-vault init ROLE
lm-dev-vault get PATH FIELD OUTPUT MODE
lm-dev-vault totp KEY ISSUER ACCOUNT OUTPUT MODE

/etc/vault (0700) holds the Vault's URL (url), the role ID of the instance's AppRole (role-id) and its secret ID
(secret-id), both 0600. init takes the secret ID from the wrapping token in secret-id.wrapped, which is removed: the
token's creation path must be the secret-id request of the role ROLE, and it is unwrapped once. get logs in and writes
the field FIELD of the KV v2 secret PATH to OUTPUT with MODE, octal. totp logs in, has the Vault generate the TOTP key
KEY for ACCOUNT of ISSUER, SHA1, 6 digits and 30 seconds, and writes its otpauth URI to OUTPUT with MODE. No argument
is a secret.
"""

import json
import os
import pathlib
import stat
import sys
import urllib.error
import urllib.request

ETC = pathlib.Path('/etc/vault')
KV_MOUNT = 'kv'
TOTP_MOUNT = 'totp'


def call(path, body=None, token=None, method='POST'):
    """Send the request to the Vault; the JSON answer."""
    url = (ETC / 'url').read_text(encoding='utf-8').strip()
    headers = {'Content-Type': 'application/json'}
    if token:
        headers['X-Vault-Token'] = token
    request = urllib.request.Request(url.rstrip('/') + path, json.dumps(body).encode() if body is not None else None,
                                     headers, method=method)
    try:
        with urllib.request.urlopen(request, timeout=30) as response:
            return json.loads(response.read() or b'{}')
    except urllib.error.HTTPError as error:
        sys.exit(f'lm-dev-vault: {method} {path}: {error.code}')
    except (urllib.error.URLError, OSError) as error:
        sys.exit(f'lm-dev-vault: {url} cannot be reached: {error}')


def write(output, text, mode):
    """Write the text to the regular file output with the octal mode."""
    descriptor = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, int(mode, 8))
    if not stat.S_ISREG(os.fstat(descriptor).st_mode):
        os.close(descriptor)
        sys.exit(f'lm-dev-vault: {output} is not a regular file')
    os.ftruncate(descriptor, 0)
    os.fchmod(descriptor, int(mode, 8))
    with os.fdopen(descriptor, 'w', encoding='utf-8') as handle:
        handle.write(text)


def login():
    """A token of the instance's AppRole."""
    answer = call('/v1/auth/approle/login', {'role_id': (ETC / 'role-id').read_text(encoding='utf-8').strip(),
                                             'secret_id': (ETC / 'secret-id').read_text(encoding='utf-8').strip()})
    return answer['auth']['client_token']


def main():
    action, arguments = (sys.argv[1], sys.argv[2:]) if len(sys.argv) > 1 else (None, [])
    if action == 'init' and len(arguments) == 1:
        wrapped = ETC / 'secret-id.wrapped'
        try:
            token = wrapped.read_text(encoding='utf-8').strip()
        finally:
            wrapped.unlink(missing_ok=True)
        expected = f'auth/approle/role/{arguments[0]}/secret-id'
        created = call('/v1/sys/wrapping/lookup', {'token': token}).get('data', {}).get('creation_path')
        if created != expected:
            sys.exit(f'lm-dev-vault: the token wraps {created}, not {expected}')
        write(ETC / 'secret-id', call('/v1/sys/wrapping/unwrap', token=token)['data']['secret_id'] + '\n', '0600')
    elif action == 'get' and len(arguments) == 4:
        path, field, output, mode = arguments
        values = call(f'/v1/{KV_MOUNT}/data/{path}', token=login(), method='GET')['data']['data']
        if field not in values:
            sys.exit(f'lm-dev-vault: {path} has no {field}')
        write(output, values[field], mode)
    elif action == 'totp' and len(arguments) == 5:
        key, issuer, account, output, mode = arguments
        answer = call(f'/v1/{TOTP_MOUNT}/keys/{key}',
                      {'generate': True, 'exported': True, 'qr_size': 0, 'issuer': issuer, 'account_name': account,
                       'algorithm': 'SHA1', 'digits': 6, 'period': 30}, token=login())
        write(output, answer['data']['url'] + '\n', mode)
    else:
        sys.exit('usage: lm-dev-vault init ROLE | get PATH FIELD OUTPUT MODE | totp KEY ISSUER ACCOUNT OUTPUT MODE')


if __name__ == '__main__':
    main()
