#!/usr/bin/env bash
# Copyright 2020 Curtin University
#
# 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.

# Author: James Diprose

# This script is run as the airflow user

########################################
# Install editable mode Python packages
########################################

{% for package in config.python_packages %}
{% if package.type == 'editable' -%}
cd /opt/{{ package.name }}
export PBR_VERSION=0.0.1
pip3 install -e . --user
unset PBR_VERSION
{% endif %}
{% endfor %}

# Initialise or upgrade the Airflow database and create the admin user
# Only run if webserver is command as there should only be one webserver
if [ "$1" = "webserver" ]; then
  echo "Running database and admin user creation commands on webserver"

  # Initialise / upgrade the Airflow database
  echo "Running command: airflow db upgrade"
  airflow db upgrade

  #Create the Admin user. This command will just print "airflow already exist in the db" if the user already exists
  echo "Running command: airflow users create"
  airflow users create -r Admin -u ${AIRFLOW_UI_USER_EMAIL} -e ${AIRFLOW_UI_USER_EMAIL} -f Observatory -l Admin -p ${AIRFLOW_UI_USER_PASSWORD}
fi

# Enter airflow home folder. Must be in the AIRFLOW_HOME folder (i.e. /opt/airflow) before running the next command
# otherwise the system will start but the workers and scheduler will not find the DAGs and other files because
# they look for them based on the current working directory.
cd ${AIRFLOW_HOME}

# Run entrypoint given by airflow docker file
/usr/bin/dumb-init -- /entrypoint "$@"
