#!/bin/bash

# Script recreating the TEST API database and starting the serveur

set -e

# Le répertoire de ce script:
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"

while getopts "p:" opt; do
  case "$opt" in
    p)
    PORT=${OPTARG}
    ;;
    \?)
	echo "Invalid option: -$OPTARG" >&2
	exit 1
	;;
    :)
	echo "Option -$OPTARG requires an argument." >&2
	exit 1
	;;
  esac
done

# récupère API_USER et API_PASSWORD
source "$SCRIPT_DIR"/.env

export FLASK_ENV=test_api
export FLASK_DEBUG=1 
tools/create_database.sh --drop SCODOC_TEST_API
flask db upgrade
flask sco-db-init --erase
flask init-test-database

flask user-create "$API_USER" LecteurAPI @all
flask user-password --password "$API_PASSWORD" "$API_USER"
flask edit-role LecteurAPI -a ScoView
flask user-role "$API_USER" -a LecteurAPI

if [ -z "$PORT" ]
then 
    flask run --host 0.0.0.0
else
    flask run --host 0.0.0.0 -p "$PORT"
fi