#!/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
    -r, --redact  redact secrets

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
github.com/KenKundert/postmortem.

You can unpack an encrypted output file using::

    gpg -d -o - name.tgz.gpg | tar zxf -
"""

# Imports {{{1
from avendesora import PasswordGenerator, PasswordError
from avendesora.gpg import PythonFile
from inform import (
    Error, conjoin, cull, display, error, 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.3.0'
__released__ = '2019-04-28'

avendesora_header = dedent('''
    # Exported Avendesora Accounts
    #
    # To adopt these accounts, you should copy this file into your existing
    # Avendesora directory: ~/.config/avendesora (you can rename this file
    # but keep the extension the same).  Then add the name of this file to the
    # accounts_files list in the ~/.config/avendesora/accounts_files file.  You
    # may then find that the account names and aliases from this file conflict
    # with your current accounts, in which case you can change the names of the
    # accounts and aliases in this file.
    #
    # Exported accounts should only be used for archival purposes. Any generated
    # secrets these accounts once contained have all be converted to obscured
    # secrets. If, at some point, it becomes necessary to change a secret, the
    # secret should be converted back to a generated secret to preserve its
    # unpredictability.

    # Imports {fold}1
    from avendesora import (
        # Basics
        Account, Hide, Hidden, GPG, Script,

        # Character sets
        exclude, LOWERCASE, UPPERCASE, LETTERS, DIGITS, ALPHANUMERIC,
        HEXDIGITS, PUNCTUATION, SYMBOLS, WHITESPACE, PRINTABLE, DISTINGUISHABLE,

        # Secrets
        Password, Passphrase, PIN, Question, MixedPassword, PasswordRecipe,
        BirthDate, OTP,

        # Account Discovery
        RecognizeAll, RecognizeAny, RecognizeTitle, RecognizeURL, RecognizeCWD,
        RecognizeHost, RecognizeUser, RecognizeEnvVar, RecognizeNetwork,
        RecognizeFile
    )
''').format(fold='{''{''{')

# 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']
    redact = cmdline['--redact']

    # Scan accounts and gather information for recipients {{{1
    pw = PasswordGenerator()
    accounts = {}
    avendesora_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:

                # create textual version of account
                # 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 field, keys in account.get_fields():
                    if field in [avendesora_recipients_fieldname, 'desc', 'NAME']:
                        continue
                    if keys == [None]:
                        v = account.get_value(field)
                        if redact and v.is_secret:
                            lines += v.render('{n}: <redacted>').split('\n')
                        else:
                            lines += v.render('{n}: {v}').split('\n')
                    else:
                        lines.append(field + ':')
                        for k, v in account.get_values(field):
                            if redact and v.is_secret:
                                lines += v.render('{k}: <redacted>').split('\n')
                            else:
                                lines += indent(
                                    v.render(('{k}) {d}: {v}', '{k}: {v}'))
                                ).split('\n')

                # add textual version of account to accounts
                if name not in accounts:
                    accounts[name] = []
                accounts[name].append('\n'.join(lines))

                # add code version of account to avendesora_accounts
                if not redact:
                    if name not in avendesora_accounts:
                        avendesora_accounts[name] = []
                    avendesora_accounts[name].append(account.export())

    # 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)

        # generates avendesora_accounts.gpg
        if name in avendesora_accounts:
            content = [avendesora_header.strip()] + avendesora_accounts[name]
            num_accounts = len(avendesora_accounts[name])
            encrypted = gpg.encrypt('\n\n'.join(content), idents, armor='always')
            if not encrypted.ok:
                raise Error(
                    'unable to encrypt:', encrypted.stderr, culprit=name
                )
            if not redact:
                try:
                    file_path = dir_path / 'avendesora_accounts.gpg'
                    file_path.write_text(str(encrypted))
                except OSError as e:
                    raise Error(os_error(e))

        # 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:
    error(os_error(e))

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