#!/usr/bin/env bash
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Wrapper for genearing PyCharm-compatible virtualenv.
set -e

HERE=$(cd `dirname "${BASH_SOURCE[0]}"` && pwd)
BUILDROOT=$HERE/../..
VENV_DIR=build-support/python/pycharm.venv
PROJECT_NAME=${PWD##*/}

function read_pants_option() {
  local -r scope="$1"
  local -r name="$2"

  ./pants options --output-format=json --scope="${scope}" --name="${name}" | python <(cat << EOF
import json, sys

print(json.load(sys.stdin)["${scope}.${name}"]["value"])
EOF
)
}

pushd "$BUILDROOT"
  ./pants dependencies --external-only src/test/python:: | sort -u > requirements.txt
  ./pants setup-py api/src/main/thrift/org/apache/aurora/gen
  ./pants setup-py api/src/main/thrift/org/apache/thermos

  rm -rf "$VENV_DIR"
  ./build-support/virtualenv "$VENV_DIR"
  source $VENV_DIR/bin/activate
    python -m pip install -U pip
    python -m pip install -r requirements.txt
    python -m pip install -f dist \
      apache.aurora.thrift==$(<.auroraversion) \
      apache.thermos.thrift==$(<.auroraversion)
    # Use same py.test version embedded into pants
    python -m pip install \
      $(read_pants_option pytest requirements) \
      $(read_pants_option pytest cov_requirements)
  deactivate
popd

if [ ! -d .idea ]; then
  echo "Creating PyCharm project at .idea/$PROJECT_NAME.iml"
  mkdir .idea
  cat <<"EOF" > .idea/$PROJECT_NAME.iml
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
  <component name="NewModuleRootManager">
    <content url="file://$MODULE_DIR$">
      <sourceFolder url="file://$MODULE_DIR$/src/main/python" isTestSource="false" />
      <excludeFolder url="file://$MODULE_DIR$/.pants.d" />
      <excludeFolder url="file://$MODULE_DIR$/dist" />
      <excludeFolder url="file://$MODULE_DIR$/out" />
    </content>
    <orderEntry type="sourceFolder" forTests="false" />
  </component>
  <component name="TestRunnerService">
    <option name="projectConfiguration" value="py.test" />
    <option name="PROJECT_TEST_RUNNER" value="py.test" />
  </component>
</module>
EOF
fi

echo "Your PyCharm environment is now set up.  You can open the project root
directory with PyCharm.

Once the project is loaded:
  - open project settings
  - click 'Project Interpreter'
  - click the cog in the upper-right corner
  - click 'Add Local'
  - select '$VENV_DIR/bin/python'
  - click 'OK'

Once this is done, all imports should be recognized, and you can run unit tests in the IDE!"
