#!/bin/bash
# Script de manipulation d'un mattermost'
# init /versions / restart ...
#

KAZ_ROOT=$(cd "$(dirname $0)"/..; pwd)
. $KAZ_ROOT/bin/.commonFunctions.sh
setKazVars
. $DOCKERS_ENV

#GLOBAL VARS
PRG=$(basename $0)

availableOrga=($(getList "${KAZ_CONF_DIR}/container-orga.list"))
AVAILABLE_ORGAS=${availableOrga[*]//-orga/}

QUIET="1"
ONNAS=

AGORACOMMUN="OUI_PAR_DEFAUT"
DockerServName=${mattermostServName}

declare -A Posts

usage() {
echo "${PRG} [OPTION] [COMMANDES] [ORGA]
Manipulation d'un mattermost

OPTIONS 
 -h|--help          Cette aide :-)
 -n|--simu          SIMULATION
 -q|--quiet         On ne parle pas (utile avec le -n pour avoir que les commandes)
 --nas              L'orga se trouve sur le NAS !

COMMANDES (on peut en mettre plusieurs dans l'ordre souhaité)
 -I|--install       L'initialisation du mattermost
 -v|--version       Donne la version du mattermost et signale les MàJ


 -mmctl \"command\"   Envoie une commande via mmctl                                         **  SPECIFIQUES  **
 -p|--post \"team\" \"message\"  Poste un message dans une team agora                         **      AGORA    **

ORGA                parmi : ${AVAILABLE_ORGAS}
                    ou vide si mattermost commun
"
}


Init(){
    NOM=$ORGA
    if [ -n "$AGORACOMMUN" ] ; then NOM="KAZ" ; fi
    CONF_FILE="${DOCK_VOL}/orga_${ORGA}-matterConfig/_data/config.json"
    if [ -n "${AGORACOMMUN}" ]; then 
        CONF_FILE="${DOCK_VOL}/mattermost_matterConfig/_data/config.json"
    elif [ -n "${ONNAS}" ]; then 
        CONF_FILE="${NAS_VOL}/orga_${ORGA}-matterConfig/_data/config.json"
    fi


    ${SIMU} sed -i \
        -e 's|"SiteURL": ".*"|"SiteURL": "'${MATTER_URL}'"|g' \
        -e 's|"ListenAddress": ".*"|"ListenAddress": ":'${matterPort}'"|g' \
        -e 's|"WebsocketURL": ".*"|"WebsocketURL": "wss://'${MATTER_URI}'"|g' \
        -e 's|"AllowCorsFrom": ".*"|"AllowCorsFrom": "'${domain}' '${MATTER_URI}':443 '${MATTER_URI}'"|g' \
        -e 's|"ConsoleLevel": ".*"|"ConsoleLevel": "ERROR"|g' \
        -e 's|"SendEmailNotifications": false|"SendEmailNotifications": true|g' \
        -e 's|"FeedbackEmail": ".*"|"FeedbackEmail": "admin@'${domain}'"|g' \
        -e 's|"FeedbackOrganization": ".*"|"FeedbackOrganization": "Cochez la KAZ du libre !"|g' \
        -e 's|"ReplyToAddress": ".*"|"ReplyToAddress": "admin@'${domain}'"|g' \
        -e 's|"SMTPServer": ".*"|"SMTPServer": "mail.'${domain}'"|g' \
        -e 's|"SMTPPort": ".*"|"SMTPPort": "25"|g' \
        -e 's|"DefaultServerLocale": ".*"|"DefaultServerLocale": "fr"|g' \
        -e 's|"DefaultClientLocale": ".*"|"DefaultClientLocale": "fr"|g' \
        -e 's|"AvailableLocales": ".*"|"AvailableLocales": "fr"|g' \
        ${CONF_FILE}

    # on redémarre pour prendre en compte (changement de port)
    ${SIMU} docker restart "${DockerServName}"
    [ $? -ne 0 ] && printKazError "$DockerServName est down : impossible de terminer l'install" && return 1 >& $QUIET

    ${SIMU} waitUrl "$MATTER_URL" 300
    [ $? -ne 0 ] && printKazError "$DockerServName ne parvient pas à démarrer correctement : impossible de terminer l'install" && return 1 >& $QUIET

    # creation compte admin
    _getPasswords
    ${SIMU} curl -i -d "{\"email\":\"${MM_ADMIN_EMAIL}\",\"username\":\"${mattermost_user}\",\"password\":\"${mattermost_pass}\",\"allow_marketing\":true}" "${MATTER_URL}/api/v4/users"

    MM_TOKEN=$(_getMMToken ${MATTER_URL})

    #on crée la team
    ${SIMU} curl -i -H "Authorization: Bearer ${MM_TOKEN}" -d "{\"display_name\":\"${NOM}\",\"name\":\"${NOM,,}\",\"type\":\"O\"}" "${MATTER_URL}/api/v4/teams"
}

Version(){
    VERSION=$(docker exec "$DockerServName" bin/mmctl version | grep -i version:)
    echo "Version $DockerServName : ${GREEN}${VERSION}${NC}"
}

_getMMToken(){
    #$1 MATTER_URL
    _getPasswords
    ${SIMU} curl -i -s -d "{\"login_id\":\"${mattermost_user}\",\"password\":\"${mattermost_pass}\"}" "${1}/api/v4/users/login" | grep 'token' | sed 's/token:\s*\(.*\)\s*/\1/' | tr -d '\r'
}

PostMessage(){
    printKazMsg "Envoi à $TEAM : $MESSAGE" >& $QUIET
    _getPasswords
    ${SIMU} docker exec -ti "${DockerServName}" bin/mmctl auth login "${MATTER_URL}" --name local-server --username ${mattermost_user} --password ${mattermost_pass}
    ${SIMU} docker exec -ti "${DockerServName}" bin/mmctl post create "${TEAM}" --message "${MESSAGE}"
}

MmctlCommand(){
    # $1 command
    ${SIMU} docker exec -u 33 "$DockerServName" bin/mmctl $1
}

_getPasswords(){
    # récupération des infos du compte admin
    if [ -n "$AGORACOMMUN" ] ; then 
        . $KAZ_KEY_DIR/env-mattermostAdmin
        . $KAZ_KEY_DIR/env-mattermostServ
    else
        . $KAZ_KEY_DIR/orgas/${ORGA}/env-mattermostAdmin
        . $KAZ_KEY_DIR/orgas/$ORGA/env-mattermostServ
    fi
}

########## Main #################
for ARG in "$@"; do
    if [ -n  "${GETMMCTLCOMAND}" ]; then # après un -mmctl
        MMCTLCOMAND="${ARG}"
        GETMMCTLCOMAND=
    elif [ -n  "${GETTEAM}" ]; then # après un --post
        GETMESSAGE="now"
        GETTEAM=""
        TEAM="${ARG}"
    elif [ -n  "${GETMESSAGE}" ]; then # après un --post "team:channel"
        if [[ $TEAM == "-*" && ${#TEAM} -le 5 ]]; then echo "J'envoie mon message à \"${TEAM}\" ?? Arf, ça me plait pas j'ai l'impression que tu t'es planté sur la commande."; usage ; exit 1 ; fi
        if [[ $ARG == "-*" && ${#ARG} -le 5 ]]; then echo "J'envoie le message \"${ARG}\" ?? Arf, ça me plait pas j'ai l'impression que tu t'es planté sur la commande."; usage ; exit 1 ; fi
        if [[ ! $TEAM =~ .*:.+ ]]; then  echo "Il faut mettre un destinataire sous la forme team:channel. Recommence !"; usage ; exit 1 ; fi
        MESSAGE="$ARG"
        GETMESSAGE=""
    else 
        case "${ARG}" in
            '-h' | '--help' )
            usage && exit ;;
            '-n' | '--simu')
            SIMU="echo" ;;
            '-q' )
            QUIET="/dev/null" ;;
            '--nas' | '-nas' )
            ONNAS="SURNAS" ;; 
            '-v' | '--version')
            COMMANDS="$(echo "${COMMANDS} VERSION" | sed "s/\s/\n/g" | sort | uniq)" ;; 
            '-I' | '--install' )
            COMMANDS="$(echo "${COMMANDS} INIT" | sed "s/\s/\n/g" | sort | uniq)" ;; # le sed sort uniq, c'est pour pas l'avoir en double
            '--mmctl' | '-mmctl' )
            COMMANDS="$(echo "${COMMANDS} RUN-AGORA-MMCTL" | sed "s/\s/\n/g" | sort | uniq)"
            GETMMCTLCOMAND="now" ;;
            '-p' | '--post' )
            COMMANDS="$(echo "${COMMANDS} POST-AGORA" | sed "s/\s/\n/g" | sort | uniq)"
            GETTEAM="now" ;;
            '-*' ) # ignore
            ;; 
            *)
            ORGA="${ARG%-orga}"
            DockerServName="${ORGA}-${mattermostServName}"
            AGORACOMMUN=
            ;;
        esac
    fi
done

if [ -z "${COMMANDS}" ]; then usage && exit ; fi

MATTER_URI="${ORGA}-${matterHost}.${domain}"
if [ -n "$AGORACOMMUN" ]; then MATTER_URI="${matterHost}.${domain}" ; fi
MATTER_URL="${httpProto}://${MATTER_URI}"

for COMMAND in ${COMMANDS}; do
    case "${COMMAND}" in
        'VERSION' )
         Version && exit ;;
        'INIT' )
         Init ;;
        'RUN-AGORA-MMCTL' )
         MmctlCommand "$MMCTLCOMAND" ;;
        'POST-AGORA' )
         PostMessage ;;
    esac
done
