#!/usr/bin/env python3
import subprocess
import tempfile
import argparse
import hashlib
import tarfile
import json
import sys
import os
parser = argparse.ArgumentParser()
parser.add_argument("tarfile", type = argparse.FileType("wb"), help = "tarball to create")
parser.add_argument("firmware", nargs = "+", help = "firmware files to stuff into tarball")
args = parser.parse_args()
tar = tarfile.TarFile.open(fileobj = args.tarfile, mode = "w|gz")
head = subprocess.check_output(("git", "rev-parse", "HEAD")).decode().strip()
time = subprocess.check_output(("git", "show", "-s", "--format=%ct", "HEAD")).decode().strip()
commits = dict((path, hash) for hash, path, branch in
(line.decode().split() for line in subprocess.check_output(("git", "submodule", "status")).splitlines()))
sha256 = {}
for fn in args.firmware:
with open(fn, "rb") as f:
sha256[os.path.basename(fn)] = hashlib.sha256(f.read()).hexdigest()
tar.add(fn, os.path.basename(fn))
manifest = json.dumps(dict(head = head, time = time, commits = commits, sha256 = sha256), indent = 2, sort_keys = True)
if os.path.isdir(os.getenv("GNUPGHOME", "")):
gpg = subprocess.Popen(("gpg", "--clearsign", "--personal-digest-preferences", "SHA256", "--no-permission-warning"),
stdin = subprocess.PIPE, stdout = subprocess.PIPE, universal_newlines = True)
manifest = gpg.communicate(manifest)[0]
if gpg.returncode:
sys.exit("gpg failed")
with tempfile.NamedTemporaryFile("w+") as f:
os.fchmod(f.fileno(), 0o644)
f.write(manifest)
f.seek(0)
tar.add(f.name, "MANIFEST")
tar.close()
args.tarfile.close()