#!/usr/bin/env python3
"""Download RHGitaly source tarball, checks signature

This is meant to be run from the root of the Heptapod Rails checkout.
The resulting path is printed on stdout.

Download and signature details end up on stderr.
"""
import argparse
from hashlib import sha256
import os
import subprocess
from sys import stderr

parser = argparse.ArgumentParser()
parser.add_argument('--unpack', action='store_true',
                    help="Unpack the tarball and output the resulting "
                    "directory path"
                    )
parser.add_argument('--sha256', action='store_true',
                    help="Compute the SHA256 sum and output it instead of "
                    "the tarball path. It is guaranteed to be correct, thanks "
                    "to the GPG signature check.")

cl_args = parser.parse_args()

CWD = os.getcwd()

RHGITALY_DOWNLOAD_BASE_URL = 'https://upload.heptapod.net/rhgitaly'


def download_fixed_rhgitaly(unpack=False, checksum=False):
    with open(os.path.join(CWD, 'RHGITALY_SERVER_VERSION')) as vf:
        version = vf.read().strip()
    tmp_path = os.path.join(CWD, 'tmp', 'tests')
    tarball_path = os.path.join(tmp_path, f'rhgitaly-{version}.tgz')
    tarball_url = f'{RHGITALY_DOWNLOAD_BASE_URL}/rhgitaly-{version}.tgz'
    stderr.write(f"Downloading {tarball_url} and its detached signature\n")
    subprocess.check_call(('curl', '-s', '-o', tarball_path, tarball_url))

    sig_path = tarball_path + '.asc'
    sig_url = tarball_url + '.asc'
    subprocess.check_call(('curl', '-s', '-o', sig_path, sig_url))
    stderr.write("Checking signature\n")
    subprocess.check_call(
        ('gpgv',
         # do not ever use a file name as relative paths here,
         # they would be interpreted relative to ~/.gnupg
         '--keyring', os.path.join(CWD, 'scripts', 'heptapod-pub-keyring.gpg'),
         sig_path, tarball_path,
         )
    )
    output = tarball_path

    if unpack:
        subprocess.check_call(('tar', '-C', tmp_path, '-xzf', tarball_path))
        output = os.path.join(tmp_path, f'rhgitaly-{version}')

    if checksum:
        with open(tarball_path, 'rb') as tarf:
            # HGitaly tarball being small (271kB as of this writing),
            # we don't bother reading it in chunks.
            output = sha256(tarf.read()).hexdigest()

    return output


print(download_fixed_rhgitaly(unpack=cl_args.unpack,
                              checksum=cl_args.sha256))
