#!/bin/bash
set -e

# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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 script that launches Python Build Pack
#  At the moment, this just launches the appropriate
#  python script.  However, this is here in case the
#  build pack needs to do anything to bootstrap the
#  python scripts, like install Python.
BP=$(dirname $(dirname $0))

BUILD_DIR=${1:-}
CACHE_DIR=${2:-}
DEPS_DIR=${3:-}
PROFILE_DIR=${5:-}

BUILDPACK_PATH=$BP
export BUILDPACK_PATH
source $BP/compile-extensions/lib/common

$BP/compile-extensions/bin/check_stack_support
$BP/compile-extensions/bin/check_buildpack_version $BP $CACHE_DIR

env_vars=$($BP/compile-extensions/bin/build_path_from_supply $DEPS_DIR)
for env_var in $env_vars; do
  export $env_var
done

export PYTHONPATH=$BP/lib

python $BP/scripts/compile.py $BUILD_DIR $CACHE_DIR

pushd $BUILD_DIR/.profile.d > /dev/null
  for f in *; do mv "$f" "finalize_$f"; done
popd > /dev/null

$BP/compile-extensions/bin/write_profiled_from_supply $DEPS_DIR $BUILD_DIR $PROFILE_DIR
$BP/compile-extensions/bin/store_buildpack_metadata $BP $CACHE_DIR
