#!/bin/bash

# des jolies couleurs
red=$'\e[1;31m'
grn=$'\e[1;32m'
yel=$'\e[1;33m'
blu=$'\e[1;34m'
mag=$'\e[1;35m'
cyn=$'\e[1;36m'
end=$'\e[0m'

_=${DJANGO_SETTINGS_MODULE:="portail.dev_settings"}
export DJANGO_SETTINGS_MODULE
export PYTHONUNBUFFERED=1

# Installer poetry si nécessaire
if ! command -v poetry >/dev/null 2>&1; then
  printf "\n${grn}%s${end}\n" "Installation de poetry ..."
  curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/install-poetry.py | python -
  source "$HOME/.poetry/env"
fi

# Installer volta si nécessaire
if ! command -v volta >/dev/null 2>&1; then
  printf "\n${grn}%s${end}\n" "Installation de volta ..."
  curl https://get.volta.sh | bash
fi

# Créer media/attachments si nécessaire
if [ ! -e 'backend/media/attachments' ]; then
  mkdir -p backend/media/attachments
  mkdir -p backend/media/photos/source
  mkdir -p backend/media/photos/dest
fi

# Vérifier que login_inp-net existe
if [ ! -e 'login_inp-net' ]; then
  read -r -p 'Entrez votre pseudo inp-net : ' pseudo
  echo "$pseudo" >login_inp-net
fi

printf "\n${grn}%s${end}\n" "Installation des dépendances python..."
poetry install --no-root

if [ "$JS_BUILD" != "false" ]; then
  # Installation des dépendances nodejs
  printf "\n${grn}%s${end}\n" "yarn install..."
  volta run yarn install
  printf "\n${grn}%s${end}\n" "gulp build..."
  volta run yarn build
fi

# script tunnel LDAP
source "scripts/tunnel_ldap.sh"

# fermeture d'un tunnel LDAP rémanent
tunnel_close

# création d'un tunnel LDAP
printf "\n${grn}%s${end}\n" "Lancement du tunnel LDAP..."
if ! tunnel_start; then
  printf "${red}%s${end}\n" "La création du tunnel SSH pour accéder au LDAP a échoué" >>/dev/stderr
  tunnel_close
  exit 1
else
  printf "${grn}%s${end}\n" "Tunnel LDAP établi"
fi

printf "\n${grn}%s${end}\n" "Migration de la base de donnée..."
poetry run ./backend/manage.py migrate
