#!/usr/bin/env python3
# Description {{{1
"""Postmortem

Generate an account summary that includes complete account information, 
including secrets, for selected accounts. This summary should allow the 
recipients to access your accounts. The summaries are intended to be given to 
the recipients after you die.

Usage:
    postmortem [options] [<recipients>...]

Options:
    -s, --send  send encrypted packet to recipient

Choose from: {available}.  If no recipients are specified, then summaries will 
be generated for all recipients.

A description of how to configure and use this program can be found at 
`<https://avendesora.readthedocs.io/en/latest/api.html#example-postmortem-summaries>_.
"""

# Imports {{{1
from avendesora import PasswordGenerator, PasswordError
from avendesora.gpg import PythonFile
from inform import (
    Error, conjoin, cull, display, indent, os_error, terminate, warn, is_str
)
from docopt import docopt
from appdirs import user_config_dir
from shlib import to_path, mkdir, cp, rm, set_prefs as shlib_set_prefs, Run
from textwrap import dedent
import arrow
import gnupg

# Settings {{{1
prog_name = 'postmortem'
config_filename = 'config'
shlib_set_prefs(use_inform=True)
__version__ = '0.0.0'
__released__ = '2019-01-03'

# these can be overridden in the settings file: ~/.config/postmortem
my_gpg_ids = ''
recipients = dict()
avendesora_value_fieldname = 'estimated_value'
avendesora_recipients_fieldname = 'postmortem_recipients'
now = arrow.now()

try:
    # Read settings {{{1
    config_filepath = to_path(user_config_dir(prog_name), config_filename)
    if config_filepath.exists():
        settings = PythonFile(config_filepath)
        settings.initialize()
        locals().update(settings.run())
    else:
        warn('no configuration file found.')

    # Read command line and process options {{{1
    cmdline = docopt(__doc__.format(available=conjoin(recipients)))
    who = cmdline['<recipients>']
    if not who:
        who = recipients
    send = cmdline['--send']

    # Scan accounts and gather information for recipients {{{1
    pw = PasswordGenerator()
    accounts = {}
    for account in pw.all_accounts():
        account_name = account.get_name()
        class_name = account.__name__
        description = account.get_scalar('desc', None, None)

        # summarize account values {{{2
        data = account.get_composite(avendesora_value_fieldname)
        postmortem_recipients = account.get_scalar(avendesora_recipients_fieldname, default=None)
        if data and not postmortem_recipients:
            warn('no recipients.', culprit= account.get_name())
            continue
        if not postmortem_recipients:
            continue
        postmortem_recipients = postmortem_recipients.split()

        # gather information for recipients {{{2
        for name, recipient in recipients.items():
            if recipient.get('category') in postmortem_recipients:
                # output title
                title = ' - '.join(cull([class_name, description]))
                lines = [title, len(title)*'=']

                # output avendesora names
                aliases = account.get_composite('aliases')
                names = [account_name] + (aliases if aliases else [])
                lines.append('avendesora names: ' + ', '.join(names))

                # output user fields
                for key, field in account.get_fields():
                    if key in [avendesora_recipients_fieldname, 'desc', 'NAME']:
                        continue
                    if field:
                        lines.append(key + ':')
                        for k, v in account.get_values(key):
                            lines += indent(
                                v.render(('{k}) {d}: {v}', '{k}: {v}'))
                            ).split('\n')
                    else:
                        v = account.get_value(key)
                        lines += v.render('{n}: {v}').split('\n')
                if name not in accounts:
                    accounts[name] = []
                accounts[name].append('\n'.join(lines))

    # generate encrypted files that contain accounts for each recipient {{{1
    gpg = gnupg.GPG(gpgbinary='gpg1')
    for name, recipient in recipients.items():
        if who and name not in who:
            continue
        dir_path = to_path(name_template.format(name=name, now=now))
        rm(dir_path)
        mkdir(dir_path)
        idents = (
            recipient.get('gpg_id', recipient.get('email')).split()
          + my_gpg_ids.split()
        )

        # copy in extras
        for each in recipient.get('extras', []):
            cp(each, dir_path)

        # generate networth report
        profile = recipient.get('networth')
        if profile:
            cmd = 'networth'.split()
            if is_str(profile):
                cmd.append(profile)
            nw = Run(cmd, 'sOeW')
            file_path = dir_path / 'networth'
            file_path.write_text(nw.stdout)

        # generates accounts.gpg
        if name in accounts:
            content = accounts[name]
            num_accounts = len(content)
            encrypted = gpg.encrypt('\n\n\n'.join(content), idents, armor='always')
            if not encrypted.ok:
                raise Error(
                    'unable to encrypt:', encrypted.stderr, culprit=name
                )
            try:
                file_path = dir_path / 'accounts.gpg'
                file_path.write_text(str(encrypted))
                display(f'contains {num_accounts} accounts.', culprit=name)
            except OSError as e:
                raise Error(os_error(e))
        else:
            warn('no accounts found.', culprit=name)

        # tar up directory
        tar_path = dir_path.with_suffix('.tgz')
        Run(['tar', 'zcf', tar_path, dir_path], 'soeW')

        # sign and encrypt tarfile
        tar_contents = tar_path.read_bytes()
        encrypted = gpg.encrypt(tar_contents, idents, armor='always')
        if not encrypted.ok:
            raise Error(
                'unable to encrypt:', encrypted.stderr, culprit=name
            )
        encrypted_tar_path = tar_path.with_suffix('.tgz.gpg')
        encrypted_tar_path.write_text(str(encrypted))

        # remove intermediate files & dirs
        rm(dir_path, tar_path)

        # send packet
        if send and recipient.get('email'):
            msg = dedent(f'''
                {name.title()},
                    Attached is a packet of information that should be useful
                if something were to happen to me. Please keep this information 
                secure and use it responsibly. It is encrypted with your GPG 
                key.

                You can unpack this packet using:
                    gpg --output {tar_path!s} --decrypt {encrypted_tar_path!s}
                    tar xf {tar_path!s}
            ''')
            cmd = [
                'mail',
                '-s', 'postmortem packet',
                '-a', str(encrypted_tar_path),
                recipient.get('email')
            ]
            Run(cmd, 'soeW', stdin=msg)

# process exceptions {{{1
except KeyboardInterrupt:
    terminate('Killed by user.')
except (PasswordError, Error) as e:
    e.terminate()
except OSError as e:
    raise Error(os_error(e))

# vim: set sw=4 sts=4 et:
