<NME> nightly.py
<BEF> #!/usr/bin/env python3
#
# nightly.py - part of the FDroid server tools
# Copyright (C) 2017 Hans-Christoph Steiner <hans@eds.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import base64
import datetime
import git
import hashlib
import logging
import os
import paramiko
import platform
import shutil
import subprocess
import sys
import tempfile
import yaml
from urllib.parse import urlparse
from argparse import ArgumentParser

from . import _
from . import common


# hard coded defaults for Android ~/.android/debug.keystore files
# https://developers.google.com/android/guides/client-auth
KEYSTORE_FILE = os.path.join(os.getenv('HOME'), '.android', 'debug.keystore')
PASSWORD = 'android'  # nosec B105 standard hardcoded password for debug keystores
KEY_ALIAS = 'androiddebugkey'
DISTINGUISHED_NAME = 'CN=Android Debug,O=Android,C=US'

# standard suffix for naming fdroid git repos
NIGHTLY = '-nightly'


def _ssh_key_from_debug_keystore(keystore=KEYSTORE_FILE):
    tmp_dir = tempfile.mkdtemp(prefix='.')
    privkey = os.path.join(tmp_dir, '.privkey')
    key_pem = os.path.join(tmp_dir, '.key.pem')
    p12 = os.path.join(tmp_dir, '.keystore.p12')
    _config = dict()
    common.fill_config_defaults(_config)
    subprocess.check_call(
        [
            _config['keytool'],
            '-importkeystore',
            '-srckeystore',
            keystore,
            '-srcalias',
            KEY_ALIAS,
            '-srcstorepass',
            PASSWORD,
            '-srckeypass',
            PASSWORD,
            '-destkeystore',
            p12,
            '-destalias',
            KEY_ALIAS,
            '-deststorepass',
            PASSWORD,
            '-destkeypass',
            PASSWORD,
            '-deststoretype',
            'PKCS12',
        ],
        env={'LC_ALL': 'C.UTF-8'},
    )
    subprocess.check_call(
        [
            'openssl',
            'pkcs12',
            '-in',
            p12,
            '-out',
            key_pem,
            '-passin',
            'pass:' + PASSWORD,
            '-passout',
            'pass:' + PASSWORD,
        ],
        env={'LC_ALL': 'C.UTF-8'},
    )
    subprocess.check_call(
        [
            'openssl',
            'rsa',
            '-in',
            key_pem,
            '-out',
            privkey,
            '-passin',
            'pass:' + PASSWORD,
        ],
        env={'LC_ALL': 'C.UTF-8'},
    )
    os.remove(key_pem)
    os.remove(p12)
    os.chmod(privkey, 0o600)  # os.umask() should cover this, but just in case

    rsakey = paramiko.RSAKey.from_private_key_file(privkey)
    fingerprint = (
        base64.b64encode(hashlib.sha256(rsakey.asbytes()).digest())
        .decode('ascii')
        .rstrip('=')
    )
    ssh_private_key_file = os.path.join(
        tmp_dir, 'debug_keystore_' + fingerprint.replace('/', '_') + '_id_rsa'
    )
    shutil.move(privkey, ssh_private_key_file)

    pub = rsakey.get_name() + ' ' + rsakey.get_base64() + ' ' + ssh_private_key_file
    with open(ssh_private_key_file + '.pub', 'w') as fp:
        fp.write(pub)

    logging.info(_('\nSSH public key to be used as deploy key:') + '\n' + pub)

    return ssh_private_key_file


def get_repo_base_url(clone_url, repo_git_base, force_type=None):
    if force_type is None:
        force_type = urlparse(clone_url).netloc
    if force_type == 'gitlab.com':
        return clone_url + '/-/raw/master/fdroid'
    if force_type == 'github.com':
        return 'https://raw.githubusercontent.com/%s/master/fdroid' % repo_git_base
    print(_('ERROR: unsupported git host "%s", patches welcome!') % force_type)
    sys.exit(1)


def main():

    parser = ArgumentParser()
    common.setup_global_opts(parser)
    parser.add_argument(
        "--keystore",
        default=KEYSTORE_FILE,
        help=_("Specify which debug keystore file to use."),
    )
    parser.add_argument(
        "--show-secret-var",
        action="store_true",
        default=False,
        help=_("Print the secret variable to the terminal for easy copy/paste"),
    )
    parser.add_argument(
        "--keep-private-keys",
        action="store_true",
        default=False,
        help=_("Do not remove the private keys generated from the keystore"),
    )
    parser.add_argument(
        "--no-deploy",
        action="store_true",
        default=False,
        help=_("Do not deploy the new files to the repo"),
    )
    parser.add_argument(
        "--file",
        default='app/build/outputs/apk/*.apk',
        help=_('The file to be included in the repo (path or glob)'),
    )
    parser.add_argument(
        "--no-checksum",
        action="store_true",
        default=False,
        help=_("Don't use rsync checksums"),
    )
    parser.add_argument(
        "--archive-older",
        type=int,
        default=20,
        help=_("Set maximum releases in repo before older ones are archived"),
    )
    # TODO add --with-btlog
    options = parser.parse_args()

    # force a tighter umask since this writes private key material
    umask = os.umask(0o077)

    if 'CI' in os.environ:
        v = os.getenv('DEBUG_KEYSTORE')
        debug_keystore = None
        if v:
            debug_keystore = base64.b64decode(v)
        if not debug_keystore:
            logging.error(_('DEBUG_KEYSTORE is not set or the value is incomplete'))
            sys.exit(1)
        os.makedirs(os.path.dirname(KEYSTORE_FILE), exist_ok=True)
        if os.path.exists(KEYSTORE_FILE):
            logging.warning(_('overwriting existing {path}').format(path=KEYSTORE_FILE))
        with open(KEYSTORE_FILE, 'wb') as fp:
            fp.write(debug_keystore)

        repo_basedir = os.path.join(os.getcwd(), 'fdroid')
        repodir = os.path.join(repo_basedir, 'repo')
        cibase = os.getcwd()
        os.makedirs(repodir, exist_ok=True)

        # the 'master' branch is hardcoded in fdroidserver/deploy.py
        if 'CI_PROJECT_PATH' in os.environ and 'CI_PROJECT_URL' in os.environ:
            # we are in GitLab CI
            repo_git_base = os.getenv('CI_PROJECT_PATH') + NIGHTLY
            clone_url = os.getenv('CI_PROJECT_URL') + NIGHTLY
            repo_base = get_repo_base_url(clone_url, repo_git_base, force_type='gitlab.com')
            servergitmirror = 'git@' + urlparse(clone_url).netloc + ':' + repo_git_base
            deploy_key_url = clone_url + '/-/settings/repository#js-deploy-keys-settings'
            git_user_name = os.getenv('GITLAB_USER_NAME')
            git_user_email = os.getenv('GITLAB_USER_EMAIL')
        elif 'TRAVIS_REPO_SLUG' in os.environ:
            # we are in Travis CI
            repo_git_base = os.getenv('TRAVIS_REPO_SLUG') + NIGHTLY
            clone_url = 'https://github.com/' + repo_git_base
            repo_base = get_repo_base_url(clone_url, repo_git_base, force_type='github.com')
            servergitmirror = 'git@github.com:' + repo_git_base
            deploy_key_url = ('https://github.com/' + repo_git_base + '/settings/keys'
                              + '\nhttps://developer.github.com/v3/guides/managing-deploy-keys/#deploy-keys')
            git_user_name = repo_git_base
            git_user_email = os.getenv('USER') + '@' + platform.node()
        elif (
            'CIRCLE_REPOSITORY_URL' in os.environ
            and 'CIRCLE_PROJECT_USERNAME' in os.environ
            and 'CIRCLE_PROJECT_REPONAME' in os.environ
        ):
            # we are in Circle CI
            repo_git_base = (os.getenv('CIRCLE_PROJECT_USERNAME')
                             + '/' + os.getenv('CIRCLE_PROJECT_REPONAME') + NIGHTLY)
            clone_url = os.getenv('CIRCLE_REPOSITORY_URL') + NIGHTLY
            repo_base = get_repo_base_url(clone_url, repo_git_base, force_type='github.com')
            servergitmirror = 'git@' + urlparse(clone_url).netloc + ':' + repo_git_base
            deploy_key_url = ('https://github.com/' + repo_git_base + '/settings/keys'
                              + '\nhttps://developer.github.com/v3/guides/managing-deploy-keys/#deploy-keys')
            git_user_name = os.getenv('CIRCLE_USERNAME')
            git_user_email = git_user_name + '@' + platform.node()
        common.assert_config_keystore(config)

        for root, dirs, files in os.walk(cibase):
            for d in ('fdroid', '.git', '.gradle'):
                if d in dirs:
                    dirs.remove(d)
            for f in files:
                if f.endswith('-debug.apk'):
            git_user_name = os.getenv('GITHUB_ACTOR')
            git_user_email = git_user_name + '@' + platform.node()
        else:
            print(_('ERROR: unsupported CI type, patches welcome!'))
            sys.exit(1)

        repo_url = repo_base + '/repo'
        git_mirror_path = os.path.join(repo_basedir, 'git-mirror')
        git_mirror_repodir = os.path.join(git_mirror_path, 'fdroid', 'repo')
        git_mirror_metadatadir = os.path.join(git_mirror_path, 'fdroid', 'metadata')
        git_mirror_statsdir = os.path.join(git_mirror_path, 'fdroid', 'stats')
        if not os.path.isdir(git_mirror_repodir):
            logging.debug(_('cloning {url}').format(url=clone_url))
            try:
                git.Repo.clone_from(clone_url, git_mirror_path)
            except Exception:
                pass
        if not os.path.isdir(git_mirror_repodir):
            os.makedirs(git_mirror_repodir, mode=0o755)

        mirror_git_repo = git.Repo.init(git_mirror_path)
        writer = mirror_git_repo.config_writer()
        writer.set_value('user', 'name', git_user_name)
        writer.set_value('user', 'email', git_user_email)
        writer.release()
        for remote in mirror_git_repo.remotes:
            mirror_git_repo.delete_remote(remote)

        readme_path = os.path.join(git_mirror_path, 'README.md')
        readme = '''
# {repo_git_base}

[![{repo_url}]({repo_url}/icons/icon.png)]({repo_url})

Last updated: {date}'''.format(repo_git_base=repo_git_base,
                               repo_url=repo_url,
                               date=datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S UTC'))
        with open(readme_path, 'w') as fp:
            fp.write(readme)
        mirror_git_repo.git.add(all=True)
        mirror_git_repo.index.commit("update README")

        mirror_git_repo.git.add(all=True)
        mirror_git_repo.index.commit("update repo/website icon")

        os.chdir(repo_basedir)
        if os.path.isdir(git_mirror_repodir):
            common.local_rsync(options, git_mirror_repodir + '/', 'repo/')
        if os.path.isdir(git_mirror_metadatadir):
            common.local_rsync(options, git_mirror_metadatadir + '/', 'metadata/')
        if os.path.isdir(git_mirror_statsdir):
            common.local_rsync(options, git_mirror_statsdir + '/', 'stats/')

        ssh_private_key_file = _ssh_key_from_debug_keystore()
        # this is needed for GitPython to find the SSH key
        ssh_dir = os.path.join(os.getenv('HOME'), '.ssh')
        os.makedirs(ssh_dir, exist_ok=True)
        ssh_config = os.path.join(ssh_dir, 'config')
        logging.debug(_('adding IdentityFile to {path}').format(path=ssh_config))
        with open(ssh_config, 'a') as fp:
            fp.write('\n\nHost *\n\tIdentityFile %s\n' % ssh_private_key_file)

        config = ''
        config += "identity_file = '%s'\n" % ssh_private_key_file
        config += "repo_name = '%s'\n" % repo_git_base
        config += "repo_url = '%s'\n" % repo_url
        config += "repo_description = 'Nightly builds from %s'\n" % git_user_email
        config += "archive_name = '%s'\n" % (repo_git_base + ' archive')
        config += "archive_url = '%s'\n" % (repo_base + '/archive')
        config += (
            "archive_description = 'Old nightly builds that have been archived.'\n"
        )
        config += "archive_older = %i\n" % options.archive_older
        config += "servergitmirrors = '%s'\n" % servergitmirror
        config += "keystore = '%s'\n" % KEYSTORE_FILE
        config += "repo_keyalias = '%s'\n" % KEY_ALIAS
        config += "keystorepass = '%s'\n" % PASSWORD
        config += "keypass = '%s'\n" % PASSWORD
        config += "keydname = '%s'\n" % DISTINGUISHED_NAME
        config += "make_current_version_link = False\n"
        config += "update_stats = True\n"
        with open('config.py', 'w') as fp:
            fp.write(config)
        os.chmod('config.py', 0o600)
        config = common.read_config(options)
        common.assert_config_keystore(config)

        for root, dirs, files in os.walk(cibase):
            for d in dirs:
                if d == '.git' or d == '.gradle' or (d == 'fdroid' and root == cibase):
                    dirs.remove(d)
            for f in files:
                if f.endswith('-debug.apk'):
                    apkfilename = os.path.join(root, f)
                    logging.debug(
                        _('Stripping mystery signature from {apkfilename}').format(
                            apkfilename=apkfilename
                        )
                    )
                    destapk = os.path.join(repodir, os.path.basename(f))
                    os.chmod(apkfilename, 0o644)
                    logging.debug(
                        _(
                            'Resigning {apkfilename} with provided debug.keystore'
                        ).format(apkfilename=os.path.basename(apkfilename))
                    )
                    common.sign_apk(apkfilename, destapk, KEY_ALIAS)

        if options.verbose:
            logging.debug(_('attempting bare SSH connection to test deploy key:'))
            try:
                subprocess.check_call(
                    [
                        'ssh',
                        '-Tvi',
                        ssh_private_key_file,
                        '-oIdentitiesOnly=yes',
                        '-oStrictHostKeyChecking=no',
                        servergitmirror.split(':')[0],
                    ]
                )
            except subprocess.CalledProcessError:
                pass

        app_url = clone_url[: -len(NIGHTLY)]
        template = dict()
        template['AuthorName'] = clone_url.split('/')[4]
        template['AuthorWebSite'] = '/'.join(clone_url.split('/')[:4])
        template['Categories'] = ['nightly']
        template['SourceCode'] = app_url
        template['IssueTracker'] = app_url + '/issues'
        template['Summary'] = 'Nightly build of ' + urlparse(app_url).path[1:]
        template['Description'] = template['Summary']
        with open('template.yml', 'w') as fp:
            yaml.dump(template, fp)

        subprocess.check_call(
            ['fdroid', 'update', '--rename-apks', '--create-metadata', '--verbose'],
            cwd=repo_basedir,
        )
        common.local_rsync(
            options, repo_basedir + '/metadata/', git_mirror_metadatadir + '/'
        )
        common.local_rsync(options, repo_basedir + '/stats/', git_mirror_statsdir + '/')
        mirror_git_repo.git.add(all=True)
        mirror_git_repo.index.commit("update app metadata")

        if not options.no_deploy:
            try:
                cmd = ['fdroid', 'deploy', '--verbose', '--no-keep-git-mirror-archive']
                subprocess.check_call(cmd, cwd=repo_basedir)
            except subprocess.CalledProcessError:
                logging.error(
                    _('cannot publish update, did you set the deploy key?')
                    + '\n'
                    + deploy_key_url
                )
                sys.exit(1)

        if not options.keep_private_keys:
            os.remove(KEYSTORE_FILE)
            if shutil.rmtree.avoids_symlink_attacks:
                shutil.rmtree(os.path.dirname(ssh_private_key_file))

    else:
        if not os.path.isfile(options.keystore):
            androiddir = os.path.dirname(options.keystore)
            if not os.path.exists(androiddir):
                os.mkdir(androiddir)
                logging.info(_('created {path}').format(path=androiddir))
            logging.error(_('{path} does not exist!  Create it by running:').format(path=options.keystore)
                          + '\n    keytool -genkey -v -keystore ' + options.keystore + ' -storepass android \\'
                          + '\n     -alias androiddebugkey -keypass android -keyalg RSA -keysize 2048 -validity 10000 \\'
                          + '\n     -dname "CN=Android Debug,O=Android,C=US"')
            sys.exit(1)
        ssh_dir = os.path.join(os.getenv('HOME'), '.ssh')
        os.makedirs(os.path.dirname(ssh_dir), exist_ok=True)
        privkey = _ssh_key_from_debug_keystore(options.keystore)
        ssh_private_key_file = os.path.join(ssh_dir, os.path.basename(privkey))
        shutil.move(privkey, ssh_private_key_file)
        shutil.move(privkey + '.pub', ssh_private_key_file + '.pub')
        if shutil.rmtree.avoids_symlink_attacks:
            shutil.rmtree(os.path.dirname(privkey))

        if options.show_secret_var:
            with open(options.keystore, 'rb') as fp:
                debug_keystore = base64.standard_b64encode(fp.read()).decode('ascii')
            print(
                _('\n{path} encoded for the DEBUG_KEYSTORE secret variable:').format(
                    path=options.keystore
                )
            )
            print(debug_keystore)

    os.umask(umask)


if __name__ == "__main__":
    main()

<MSG> Merge branch 'two-fixes' into 'master'

Two fixes

See merge request fdroid/fdroidserver!628
<DFF> @@ -249,8 +249,8 @@ Last updated: {date}'''.format(repo_git_base=repo_git_base,
         common.assert_config_keystore(config)
 
         for root, dirs, files in os.walk(cibase):
-            for d in ('fdroid', '.git', '.gradle'):
-                if d in dirs:
+            for d in dirs:
+                if d == '.git' or d == '.gradle' or (d == 'fdroid' and root == cibase):
                     dirs.remove(d)
             for f in files:
                 if f.endswith('-debug.apk'):

{'commit': 'diff --git a/fdroidserver/index.py b/fdroidserver/index.py\nindex d8477dc5..29027a38 100644\n--- a/fdroidserver/index.py\n+++ b/fdroidserver/index.py\n@@ -88,7 +88,7 @@ def make(apps, sortedids, apks, repodir, archive):\n \n     mirrorcheckfailed = False\n     mirrors = []\n-    for mirror in sorted(common.config.get(\'mirrors\', [])):\n+    for mirror in common.config.get(\'mirrors\', []):\n         base = os.path.basename(urllib.parse.urlparse(mirror).path.rstrip(\'/\'))\n         if common.config.get(\'nonstandardwebroot\') is not True and base != \'fdroid\':\n             logging.error(_("mirror \'%s\' does not end with \'fdroid\'!") % mirror)\ndiff --git a/fdroidserver/nightly.py b/fdroidserver/nightly.py\nindex 9579ae50..e6f766c0 100644\n--- a/fdroidserver/nightly.py\n+++ b/fdroidserver/nightly.py\n@@ -249,8 +249,8 @@ Last updated: {date}\'\'\'.format(repo_git_base=repo_git_base,\n         common.assert_config_keystore(config)\n \n         for root, dirs, files in os.walk(cibase):\n-            for d in (\'fdroid\', \'.git\', \'.gradle\'):\n-                if d in dirs:\n+            for d in dirs:\n+                if d == \'.git\' or d == \'.gradle\' or (d == \'fdroid\' and root == cibase):\n                     dirs.remove(d)\n             for f in files:\n                 if f.endswith(\'-debug.apk\'):\n', 'commit_subject': "Merge branch 'two-fixes' into 'master'", 'repo_name': 'f-droid/fdroidserver', 'committer': {'name': 'Marcus', 'email': 'e24202824e82e7d9df6e9287d0e9e567ae0c4109@bubu1.eu', 'time_sec': '1550872847', 'tz_offset': '0', 'date': {'seconds': '1550872847'}}, 'commit_tree': 'e79f9f08d60e0d01446f330552770db3072b2a59', 'commit_message': "Merge branch 'two-fixes' into 'master'\n\nTwo fixes\n\nSee merge request fdroid/fdroidserver!628", 'language_name': 'Shell', 'license': 'agpl-3.0', 'hunks': "@@ -249,8 +249,8 @@ Last updated: {date}'''.format(repo_git_base=repo_git_base,\n         common.assert_config_keystore(config)\n \n         for root, dirs, files in os.walk(cibase):\n-            for d in ('fdroid', '.git', '.gradle'):\n-                if d in dirs:\n+            for d in dirs:\n+                if d == '.git' or d == '.gradle' or (d == 'fdroid' and root == cibase):\n                     dirs.remove(d)\n             for f in files:\n                 if f.endswith('-debug.apk'):\n", 'addition_count': 2, 'deletion_count': 2, 'src_file': 'a/fdroidserver/nightly.py', 'tgt_file': 'b/fdroidserver/nightly.py', 'file_extension': '.py', 'before_file': '#!/usr/bin/env python3\n#\n# nightly.py - part of the FDroid server tools\n# Copyright (C) 2017 Hans-Christoph Steiner <hans@eds.org>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nimport base64\nimport datetime\nimport git\nimport hashlib\nimport logging\nimport os\nimport paramiko\nimport platform\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nimport yaml\nfrom urllib.parse import urlparse\nfrom argparse import ArgumentParser\n\nfrom . import _\nfrom . import common\n\n\n# hard coded defaults for Android ~/.android/debug.keystore files\n# https://developers.google.com/android/guides/client-auth\nKEYSTORE_FILE = os.path.join(os.getenv(\'HOME\'), \'.android\', \'debug.keystore\')\nPASSWORD = \'android\'  # nosec B105 standard hardcoded password for debug keystores\nKEY_ALIAS = \'androiddebugkey\'\nDISTINGUISHED_NAME = \'CN=Android Debug,O=Android,C=US\'\n\n# standard suffix for naming fdroid git repos\nNIGHTLY = \'-nightly\'\n\n\ndef _ssh_key_from_debug_keystore(keystore=KEYSTORE_FILE):\n    tmp_dir = tempfile.mkdtemp(prefix=\'.\')\n    privkey = os.path.join(tmp_dir, \'.privkey\')\n    key_pem = os.path.join(tmp_dir, \'.key.pem\')\n    p12 = os.path.join(tmp_dir, \'.keystore.p12\')\n    _config = dict()\n    common.fill_config_defaults(_config)\n    subprocess.check_call(\n        [\n            _config[\'keytool\'],\n            \'-importkeystore\',\n            \'-srckeystore\',\n            keystore,\n            \'-srcalias\',\n            KEY_ALIAS,\n            \'-srcstorepass\',\n            PASSWORD,\n            \'-srckeypass\',\n            PASSWORD,\n            \'-destkeystore\',\n            p12,\n            \'-destalias\',\n            KEY_ALIAS,\n            \'-deststorepass\',\n            PASSWORD,\n            \'-destkeypass\',\n            PASSWORD,\n            \'-deststoretype\',\n            \'PKCS12\',\n        ],\n        env={\'LC_ALL\': \'C.UTF-8\'},\n    )\n    subprocess.check_call(\n        [\n            \'openssl\',\n            \'pkcs12\',\n            \'-in\',\n            p12,\n            \'-out\',\n            key_pem,\n            \'-passin\',\n            \'pass:\' + PASSWORD,\n            \'-passout\',\n            \'pass:\' + PASSWORD,\n        ],\n        env={\'LC_ALL\': \'C.UTF-8\'},\n    )\n    subprocess.check_call(\n        [\n            \'openssl\',\n            \'rsa\',\n            \'-in\',\n            key_pem,\n            \'-out\',\n            privkey,\n            \'-passin\',\n            \'pass:\' + PASSWORD,\n        ],\n        env={\'LC_ALL\': \'C.UTF-8\'},\n    )\n    os.remove(key_pem)\n    os.remove(p12)\n    os.chmod(privkey, 0o600)  # os.umask() should cover this, but just in case\n\n    rsakey = paramiko.RSAKey.from_private_key_file(privkey)\n    fingerprint = (\n        base64.b64encode(hashlib.sha256(rsakey.asbytes()).digest())\n        .decode(\'ascii\')\n        .rstrip(\'=\')\n    )\n    ssh_private_key_file = os.path.join(\n        tmp_dir, \'debug_keystore_\' + fingerprint.replace(\'/\', \'_\') + \'_id_rsa\'\n    )\n    shutil.move(privkey, ssh_private_key_file)\n\n    pub = rsakey.get_name() + \' \' + rsakey.get_base64() + \' \' + ssh_private_key_file\n    with open(ssh_private_key_file + \'.pub\', \'w\') as fp:\n        fp.write(pub)\n\n    logging.info(_(\'\\nSSH public key to be used as deploy key:\') + \'\\n\' + pub)\n\n    return ssh_private_key_file\n\n\ndef get_repo_base_url(clone_url, repo_git_base, force_type=None):\n    if force_type is None:\n        force_type = urlparse(clone_url).netloc\n    if force_type == \'gitlab.com\':\n        return clone_url + \'/-/raw/master/fdroid\'\n    if force_type == \'github.com\':\n        return \'https://raw.githubusercontent.com/%s/master/fdroid\' % repo_git_base\n    print(_(\'ERROR: unsupported git host "%s", patches welcome!\') % force_type)\n    sys.exit(1)\n\n\ndef main():\n\n    parser = ArgumentParser()\n    common.setup_global_opts(parser)\n    parser.add_argument(\n        "--keystore",\n        default=KEYSTORE_FILE,\n        help=_("Specify which debug keystore file to use."),\n    )\n    parser.add_argument(\n        "--show-secret-var",\n        action="store_true",\n        default=False,\n        help=_("Print the secret variable to the terminal for easy copy/paste"),\n    )\n    parser.add_argument(\n        "--keep-private-keys",\n        action="store_true",\n        default=False,\n        help=_("Do not remove the private keys generated from the keystore"),\n    )\n    parser.add_argument(\n        "--no-deploy",\n        action="store_true",\n        default=False,\n        help=_("Do not deploy the new files to the repo"),\n    )\n    parser.add_argument(\n        "--file",\n        default=\'app/build/outputs/apk/*.apk\',\n        help=_(\'The file to be included in the repo (path or glob)\'),\n    )\n    parser.add_argument(\n        "--no-checksum",\n        action="store_true",\n        default=False,\n        help=_("Don\'t use rsync checksums"),\n    )\n    parser.add_argument(\n        "--archive-older",\n        type=int,\n        default=20,\n        help=_("Set maximum releases in repo before older ones are archived"),\n    )\n    # TODO add --with-btlog\n    options = parser.parse_args()\n\n    # force a tighter umask since this writes private key material\n    umask = os.umask(0o077)\n\n    if \'CI\' in os.environ:\n        v = os.getenv(\'DEBUG_KEYSTORE\')\n        debug_keystore = None\n        if v:\n            debug_keystore = base64.b64decode(v)\n        if not debug_keystore:\n            logging.error(_(\'DEBUG_KEYSTORE is not set or the value is incomplete\'))\n            sys.exit(1)\n        os.makedirs(os.path.dirname(KEYSTORE_FILE), exist_ok=True)\n        if os.path.exists(KEYSTORE_FILE):\n            logging.warning(_(\'overwriting existing {path}\').format(path=KEYSTORE_FILE))\n        with open(KEYSTORE_FILE, \'wb\') as fp:\n            fp.write(debug_keystore)\n\n        repo_basedir = os.path.join(os.getcwd(), \'fdroid\')\n        repodir = os.path.join(repo_basedir, \'repo\')\n        cibase = os.getcwd()\n        os.makedirs(repodir, exist_ok=True)\n\n        # the \'master\' branch is hardcoded in fdroidserver/deploy.py\n        if \'CI_PROJECT_PATH\' in os.environ and \'CI_PROJECT_URL\' in os.environ:\n            # we are in GitLab CI\n            repo_git_base = os.getenv(\'CI_PROJECT_PATH\') + NIGHTLY\n            clone_url = os.getenv(\'CI_PROJECT_URL\') + NIGHTLY\n            repo_base = get_repo_base_url(clone_url, repo_git_base, force_type=\'gitlab.com\')\n            servergitmirror = \'git@\' + urlparse(clone_url).netloc + \':\' + repo_git_base\n            deploy_key_url = clone_url + \'/-/settings/repository#js-deploy-keys-settings\'\n            git_user_name = os.getenv(\'GITLAB_USER_NAME\')\n            git_user_email = os.getenv(\'GITLAB_USER_EMAIL\')\n        elif \'TRAVIS_REPO_SLUG\' in os.environ:\n            # we are in Travis CI\n            repo_git_base = os.getenv(\'TRAVIS_REPO_SLUG\') + NIGHTLY\n            clone_url = \'https://github.com/\' + repo_git_base\n            repo_base = get_repo_base_url(clone_url, repo_git_base, force_type=\'github.com\')\n            servergitmirror = \'git@github.com:\' + repo_git_base\n            deploy_key_url = (\'https://github.com/\' + repo_git_base + \'/settings/keys\'\n                              + \'\\nhttps://developer.github.com/v3/guides/managing-deploy-keys/#deploy-keys\')\n            git_user_name = repo_git_base\n            git_user_email = os.getenv(\'USER\') + \'@\' + platform.node()\n        elif (\n            \'CIRCLE_REPOSITORY_URL\' in os.environ\n            and \'CIRCLE_PROJECT_USERNAME\' in os.environ\n            and \'CIRCLE_PROJECT_REPONAME\' in os.environ\n        ):\n            # we are in Circle CI\n            repo_git_base = (os.getenv(\'CIRCLE_PROJECT_USERNAME\')\n                             + \'/\' + os.getenv(\'CIRCLE_PROJECT_REPONAME\') + NIGHTLY)\n            clone_url = os.getenv(\'CIRCLE_REPOSITORY_URL\') + NIGHTLY\n            repo_base = get_repo_base_url(clone_url, repo_git_base, force_type=\'github.com\')\n            servergitmirror = \'git@\' + urlparse(clone_url).netloc + \':\' + repo_git_base\n            deploy_key_url = (\'https://github.com/\' + repo_git_base + \'/settings/keys\'\n                              + \'\\nhttps://developer.github.com/v3/guides/managing-deploy-keys/#deploy-keys\')\n            git_user_name = os.getenv(\'CIRCLE_USERNAME\')\n            git_user_email = git_user_name + \'@\' + platform.node()\n        common.assert_config_keystore(config)\n\n        for root, dirs, files in os.walk(cibase):\n            for d in (\'fdroid\', \'.git\', \'.gradle\'):\n                if d in dirs:\n                    dirs.remove(d)\n            for f in files:\n                if f.endswith(\'-debug.apk\'):\n            git_user_name = os.getenv(\'GITHUB_ACTOR\')\n            git_user_email = git_user_name + \'@\' + platform.node()\n        else:\n            print(_(\'ERROR: unsupported CI type, patches welcome!\'))\n            sys.exit(1)\n\n        repo_url = repo_base + \'/repo\'\n        git_mirror_path = os.path.join(repo_basedir, \'git-mirror\')\n        git_mirror_repodir = os.path.join(git_mirror_path, \'fdroid\', \'repo\')\n        git_mirror_metadatadir = os.path.join(git_mirror_path, \'fdroid\', \'metadata\')\n        git_mirror_statsdir = os.path.join(git_mirror_path, \'fdroid\', \'stats\')\n        if not os.path.isdir(git_mirror_repodir):\n            logging.debug(_(\'cloning {url}\').format(url=clone_url))\n            try:\n                git.Repo.clone_from(clone_url, git_mirror_path)\n            except Exception:\n                pass\n        if not os.path.isdir(git_mirror_repodir):\n            os.makedirs(git_mirror_repodir, mode=0o755)\n\n        mirror_git_repo = git.Repo.init(git_mirror_path)\n        writer = mirror_git_repo.config_writer()\n        writer.set_value(\'user\', \'name\', git_user_name)\n        writer.set_value(\'user\', \'email\', git_user_email)\n        writer.release()\n        for remote in mirror_git_repo.remotes:\n            mirror_git_repo.delete_remote(remote)\n\n        readme_path = os.path.join(git_mirror_path, \'README.md\')\n        readme = \'\'\'\n# {repo_git_base}\n\n[![{repo_url}]({repo_url}/icons/icon.png)]({repo_url})\n\nLast updated: {date}\'\'\'.format(repo_git_base=repo_git_base,\n                               repo_url=repo_url,\n                               date=datetime.datetime.utcnow().strftime(\'%Y-%m-%d %H:%M:%S UTC\'))\n        with open(readme_path, \'w\') as fp:\n            fp.write(readme)\n        mirror_git_repo.git.add(all=True)\n        mirror_git_repo.index.commit("update README")\n\n        mirror_git_repo.git.add(all=True)\n        mirror_git_repo.index.commit("update repo/website icon")\n\n        os.chdir(repo_basedir)\n        if os.path.isdir(git_mirror_repodir):\n            common.local_rsync(options, git_mirror_repodir + \'/\', \'repo/\')\n        if os.path.isdir(git_mirror_metadatadir):\n            common.local_rsync(options, git_mirror_metadatadir + \'/\', \'metadata/\')\n        if os.path.isdir(git_mirror_statsdir):\n            common.local_rsync(options, git_mirror_statsdir + \'/\', \'stats/\')\n\n        ssh_private_key_file = _ssh_key_from_debug_keystore()\n        # this is needed for GitPython to find the SSH key\n        ssh_dir = os.path.join(os.getenv(\'HOME\'), \'.ssh\')\n        os.makedirs(ssh_dir, exist_ok=True)\n        ssh_config = os.path.join(ssh_dir, \'config\')\n        logging.debug(_(\'adding IdentityFile to {path}\').format(path=ssh_config))\n        with open(ssh_config, \'a\') as fp:\n            fp.write(\'\\n\\nHost *\\n\\tIdentityFile %s\\n\' % ssh_private_key_file)\n\n        config = \'\'\n        config += "identity_file = \'%s\'\\n" % ssh_private_key_file\n        config += "repo_name = \'%s\'\\n" % repo_git_base\n        config += "repo_url = \'%s\'\\n" % repo_url\n        config += "repo_description = \'Nightly builds from %s\'\\n" % git_user_email\n        config += "archive_name = \'%s\'\\n" % (repo_git_base + \' archive\')\n        config += "archive_url = \'%s\'\\n" % (repo_base + \'/archive\')\n        config += (\n            "archive_description = \'Old nightly builds that have been archived.\'\\n"\n        )\n        config += "archive_older = %i\\n" % options.archive_older\n        config += "servergitmirrors = \'%s\'\\n" % servergitmirror\n        config += "keystore = \'%s\'\\n" % KEYSTORE_FILE\n        config += "repo_keyalias = \'%s\'\\n" % KEY_ALIAS\n        config += "keystorepass = \'%s\'\\n" % PASSWORD\n        config += "keypass = \'%s\'\\n" % PASSWORD\n        config += "keydname = \'%s\'\\n" % DISTINGUISHED_NAME\n        config += "make_current_version_link = False\\n"\n        config += "update_stats = True\\n"\n        with open(\'config.py\', \'w\') as fp:\n            fp.write(config)\n        os.chmod(\'config.py\', 0o600)\n        config = common.read_config(options)\n        common.assert_config_keystore(config)\n\n        for root, dirs, files in os.walk(cibase):\n            for d in dirs:\n                if d == \'.git\' or d == \'.gradle\' or (d == \'fdroid\' and root == cibase):\n                    dirs.remove(d)\n            for f in files:\n                if f.endswith(\'-debug.apk\'):\n                    apkfilename = os.path.join(root, f)\n                    logging.debug(\n                        _(\'Stripping mystery signature from {apkfilename}\').format(\n                            apkfilename=apkfilename\n                        )\n                    )\n                    destapk = os.path.join(repodir, os.path.basename(f))\n                    os.chmod(apkfilename, 0o644)\n                    logging.debug(\n                        _(\n                            \'Resigning {apkfilename} with provided debug.keystore\'\n                        ).format(apkfilename=os.path.basename(apkfilename))\n                    )\n                    common.sign_apk(apkfilename, destapk, KEY_ALIAS)\n\n        if options.verbose:\n            logging.debug(_(\'attempting bare SSH connection to test deploy key:\'))\n            try:\n                subprocess.check_call(\n                    [\n                        \'ssh\',\n                        \'-Tvi\',\n                        ssh_private_key_file,\n                        \'-oIdentitiesOnly=yes\',\n                        \'-oStrictHostKeyChecking=no\',\n                        servergitmirror.split(\':\')[0],\n                    ]\n                )\n            except subprocess.CalledProcessError:\n                pass\n\n        app_url = clone_url[: -len(NIGHTLY)]\n        template = dict()\n        template[\'AuthorName\'] = clone_url.split(\'/\')[4]\n        template[\'AuthorWebSite\'] = \'/\'.join(clone_url.split(\'/\')[:4])\n        template[\'Categories\'] = [\'nightly\']\n        template[\'SourceCode\'] = app_url\n        template[\'IssueTracker\'] = app_url + \'/issues\'\n        template[\'Summary\'] = \'Nightly build of \' + urlparse(app_url).path[1:]\n        template[\'Description\'] = template[\'Summary\']\n        with open(\'template.yml\', \'w\') as fp:\n            yaml.dump(template, fp)\n\n        subprocess.check_call(\n            [\'fdroid\', \'update\', \'--rename-apks\', \'--create-metadata\', \'--verbose\'],\n            cwd=repo_basedir,\n        )\n        common.local_rsync(\n            options, repo_basedir + \'/metadata/\', git_mirror_metadatadir + \'/\'\n        )\n        common.local_rsync(options, repo_basedir + \'/stats/\', git_mirror_statsdir + \'/\')\n        mirror_git_repo.git.add(all=True)\n        mirror_git_repo.index.commit("update app metadata")\n\n        if not options.no_deploy:\n            try:\n                cmd = [\'fdroid\', \'deploy\', \'--verbose\', \'--no-keep-git-mirror-archive\']\n                subprocess.check_call(cmd, cwd=repo_basedir)\n            except subprocess.CalledProcessError:\n                logging.error(\n                    _(\'cannot publish update, did you set the deploy key?\')\n                    + \'\\n\'\n                    + deploy_key_url\n                )\n                sys.exit(1)\n\n        if not options.keep_private_keys:\n            os.remove(KEYSTORE_FILE)\n            if shutil.rmtree.avoids_symlink_attacks:\n                shutil.rmtree(os.path.dirname(ssh_private_key_file))\n\n    else:\n        if not os.path.isfile(options.keystore):\n            androiddir = os.path.dirname(options.keystore)\n            if not os.path.exists(androiddir):\n                os.mkdir(androiddir)\n                logging.info(_(\'created {path}\').format(path=androiddir))\n            logging.error(_(\'{path} does not exist!  Create it by running:\').format(path=options.keystore)\n                          + \'\\n    keytool -genkey -v -keystore \' + options.keystore + \' -storepass android \\\\\'\n                          + \'\\n     -alias androiddebugkey -keypass android -keyalg RSA -keysize 2048 -validity 10000 \\\\\'\n                          + \'\\n     -dname "CN=Android Debug,O=Android,C=US"\')\n            sys.exit(1)\n        ssh_dir = os.path.join(os.getenv(\'HOME\'), \'.ssh\')\n        os.makedirs(os.path.dirname(ssh_dir), exist_ok=True)\n        privkey = _ssh_key_from_debug_keystore(options.keystore)\n        ssh_private_key_file = os.path.join(ssh_dir, os.path.basename(privkey))\n        shutil.move(privkey, ssh_private_key_file)\n        shutil.move(privkey + \'.pub\', ssh_private_key_file + \'.pub\')\n        if shutil.rmtree.avoids_symlink_attacks:\n            shutil.rmtree(os.path.dirname(privkey))\n\n        if options.show_secret_var:\n            with open(options.keystore, \'rb\') as fp:\n                debug_keystore = base64.standard_b64encode(fp.read()).decode(\'ascii\')\n            print(\n                _(\'\\n{path} encoded for the DEBUG_KEYSTORE secret variable:\').format(\n                    path=options.keystore\n                )\n            )\n            print(debug_keystore)\n\n    os.umask(umask)\n\n\nif __name__ == "__main__":\n    main()\n', 'message': "Merge branch 'two-fixes' into 'master'\n\nTwo fixes\n\nSee merge request fdroid/fdroidserver!628", 'author_name': 'Marcus', 'lang': 'py'}