|
| 1 | +#!/usr/bin/env python3.5 |
| 2 | + |
| 3 | +import itertools |
| 4 | +import os |
| 5 | +import pathlib |
| 6 | +import re |
| 7 | +import subprocess |
| 8 | +import sys |
| 9 | +import tempfile |
| 10 | + |
| 11 | +from argparse import ArgumentParser |
| 12 | +from pathlib import Path |
| 13 | + |
| 14 | +def get_data_if_file_exists(filename): |
| 15 | + if filename.is_file(): |
| 16 | + return subprocess.check_output(['gpg', '-d', str(filename)]) |
| 17 | + else: |
| 18 | + return b"" |
| 19 | + |
| 20 | +def edit(data): |
| 21 | + editor = os.getenv('EDITOR', 'vim') |
| 22 | + |
| 23 | + with tempfile.TemporaryDirectory() as tmpdir: |
| 24 | + tmpdir = Path(tmpdir) |
| 25 | + |
| 26 | + secret_file = tmpdir / 'secret' |
| 27 | + secret_file.write_bytes(data) |
| 28 | + |
| 29 | + subprocess.check_call([editor, str(secret_file.absolute())]) |
| 30 | + |
| 31 | + return secret_file.read_bytes() |
| 32 | + |
| 33 | +def get_key(keyfile): |
| 34 | + fingerprint_text = subprocess.check_output( |
| 35 | + ['gpg', '--with-fingerprint', str(keyfile)]).decode('US-ASCII') |
| 36 | + re_fp = re.compile("Key fingerprint = ([A-F0-9 ]*)") |
| 37 | + return re_fp.search(fingerprint_text).group(1).replace(' ', '') |
| 38 | + |
| 39 | +def main(args): |
| 40 | + os.umask(0o0077) |
| 41 | + |
| 42 | + parser = ArgumentParser( |
| 43 | + description=""" |
| 44 | + Edit each ENCRYPTED_FILE using $EDITOR, encrypting with all the GPG |
| 45 | + keys in ../keys. |
| 46 | + """) |
| 47 | + parser.add_argument('--re-encrypt', dest='re_encrypt', |
| 48 | + action='store_true', |
| 49 | + help="""Force re-encryption, good for when the key |
| 50 | + list changes""") |
| 51 | + parser.add_argument('ENCRYPTED_FILE', nargs='+') |
| 52 | + options = parser.parse_args(args) |
| 53 | + if len(args) < 1: |
| 54 | + parser.print_help() |
| 55 | + return 1 |
| 56 | + |
| 57 | + for filename in options.ENCRYPTED_FILE: |
| 58 | + filename =Path(filename) |
| 59 | + |
| 60 | + data = get_data_if_file_exists(filename) |
| 61 | + |
| 62 | + updated_data = edit(data) |
| 63 | + |
| 64 | + if data == updated_data and not options.re_encrypt: |
| 65 | + # No change, no need to re-encrypt |
| 66 | + continue |
| 67 | + |
| 68 | + encrypt_command = ['gpg', '-e', '-a', '--always-trust'] |
| 69 | + encrypt_command.extend(itertools.chain.from_iterable( |
| 70 | + ('-r', get_key(keyfile)) for keyfile in |
| 71 | + (Path(__file__).absolute().parent.parent / 'keys') |
| 72 | + .glob('*.asc'))) |
| 73 | + encrypted = subprocess.check_output( |
| 74 | + encrypt_command, input=updated_data).decode('US-ASCII') |
| 75 | + |
| 76 | + filename.write_text(encrypted) |
| 77 | + |
| 78 | +if __name__ == '__main__': |
| 79 | + sys.exit(main(sys.argv[1:])) |
0 commit comments