#!/usr/bin/env python3

# Copyright (C) 2020- The University of Notre Dame
# This software is distributed under the GNU General Public License.
# See the file COPYING for details.

import os
import sys
import tempfile
import argparse
import subprocess

import conda_pack

devnull = open(os.devnull, 'w')

def pack_env(spec, out):
    with tempfile.TemporaryDirectory() as env_dir:
        print('Creating temporary environment in {}'.format(env_dir))
        subprocess.check_call(['conda', 'env', 'create', '--prefix', env_dir,
            '--file', spec])
        # Bug breaks bundling common packages (e.g. python).
        # ignore_missing_files may be safe to remove in the future.
        # https://github.com/conda/conda-pack/issues/145
        conda_pack.pack(prefix=env_dir, output=out, force=True, ignore_missing_files=True)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Create a packed environment from a spec.')
    parser.add_argument('spec',
        help='Read in a spec file, or - for stdin.')
    parser.add_argument('out',
        help='Write output from conda-pack to the given file.')
    args = parser.parse_args()

    pack_env(args.spec, args.out)
