#!/bin/bash

# Lancement d'un python scodoc interactif
# dans l'environnement d'un département
# et avec chargement des scripts indiqués
# via from ... import *
#
# Si -r est utilisé, veiller à créer au préalable 
# le département via l'interface web (Zope)

usage() {
    echo "Usage: $0 [-h] [-r] [-x] dept [script...]"
    echo "Lance un environnement interactif python/ScoDoc"
    echo "    -r: supprime et recrée le département (attention: efface la base !)"
    echo "    -x: exit après exécution des scripts, donc mode non interactif"
    exit 1
}

set -euo pipefail
cd /opt/scodoc/Products/ScoDoc || exit 2
source config/config.sh
source config/utils.sh

RECREATE_DEPT=0
PYTHON_INTERACTIVE="-i"

while [ -n "$1" ]; do
    PARAM="$1"
    [ "${PARAM::1}" != "-" ] && break
    case $PARAM in
        -h | --help)
            usage
            exit 0
            ;;
        -r)
            RECREATE_DEPT=1
            ;;
        -x)
            PYTHON_INTERACTIVE=""
            ;;
        *)
            echo "ERROR: unknown parameter \"$PARAM\""
            usage
            exit 1
            ;;
    esac
    shift
done



DEPT="$1"
shift

if [ "$RECREATE_DEPT" = 1 ]
then
    cfg_pathname="${SCODOC_VAR_DIR}/config/depts/$DEPT".cfg
    if [ -e "$cfg_pathname" ]
    then
        (cd config || terminate "no config directory"; ./delete_dept.sh -n "$DEPT") || terminate "error deleting dept $DEPT"
    fi
    (cd config || terminate "no config directory"; ./create_dept.sh -n "$DEPT") || terminate "error creating dept $DEPT"
    # systemctl start scodoc
fi

cmd="from __future__ import print_function;from Zope2 import configure;configure('/opt/scodoc/etc/zope.conf');import Zope2; app=Zope2.app();from debug import *;context = go_dept(app, '""$DEPT""', verbose=False);"

for f in "$@"
do
    cmd="${cmd}exec(open(\"${f}\").read());"
done

if [ -z "$PYTHON_INTERACTIVE" ]
then
    /opt/zope213/bin/python -c "$cmd"
else
    /opt/zope213/bin/python "$PYTHON_INTERACTIVE" -c "$cmd"
fi