# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import os
import stat
import sys

# find the import for catkin's python package - either from source space or from an installed underlay
if os.path.exists(os.path.join('@catkin_EXTRAS_DIR@', 'catkinConfig.cmake.in')):
    sys.path.insert(0, os.path.join('@catkin_EXTRAS_DIR@', '..', 'python'))
try:
    from catkin.environment_cache import generate_environment_script
except ImportError:
    # search for catkin package in all workspaces and prepend to path
    for workspace in "@CATKIN_WORKSPACES@".split(';'):
        python_path = os.path.join(workspace, '@CATKIN_GLOBAL_PYTHON_DESTINATION@')
        if os.path.isdir(os.path.join(python_path, 'catkin')):
            sys.path.insert(0, python_path)
            break
    from catkin.environment_cache import generate_environment_script

code = generate_environment_script('@CATKIN_DEVEL_PREFIX@/env.@script_ext@')

output_filename = '@SETUP_DIR@/@SETUP_FILENAME@.@script_ext@'
with open(output_filename, 'w') as f:
    #print('Generate script for cached setup "%s"' % output_filename)
    f.write('\n'.join(code))

mode = os.stat(output_filename).st_mode
os.chmod(output_filename, mode | stat.S_IXUSR)
