#!/bin/bash

#
# Instance automatique
# Montages de deux fichier de log. l'utilisation de BOOT_LOG_FILE_STATUS ce fait dans _wait_for_poff_or_error du script deploy-auto

# shellcheck disable=SC1091
source ./context.sh
source ./00_logging.sh

PWD_FILE="/tmp/hapy-deploy/${VM_NAME}.pwd"

INST=$(CreoleGet module_instancie non)
FBFILE=/etc/eole/firstboot


function is_registred()
{
  enregistrement_zephir -c >/dev/null
  return $?
}

if [[ -e "${FBFILE}" ]]
then
    lgmsg "INSTANCE:DONE:do nothing because ${FBFILE} present"
    #exit 0
fi

if [[ "${INST}" == "non" ]]
then
    lgmsg "INSTANCE:RUNNING:starting instance"
    if ! is_registred
    then
        lgmsg "INSTANCE:ERROR:Server is not zephir registred"
        exit 2
    fi

    sleep 1
    # Wait for config.eol
    cnt=0
    while [[ ! -f "/etc/eole/config.eol" ]]
    do
        sleep 1
        [[ "${cnt}" == 10 ]] && break
        cnt=$((cnt+1))
        lgmsg "INSTANCE:RUNNING:waiting config.eol ($cnt)"
    done
    sleep 1

    set -o pipefail
    export LANG=fr_FR.UTF-8 
    export LC_ADDRESS=fr_FR.UTF-8
    export LC_NAME=fr_FR.UTF-8
    export LC_MONETARY=fr_FR.UTF-8
    export LC_PAPER=fr_FR.UTF-8
    export LC_IDENTIFICATION=fr_FR.UTF-8
    export LC_TELEPHONE=fr_FR.UTF-8
    export LC_MESSAGES=fr_FR.UTF-8
    export LC_MEASUREMENT=fr_FR.UTF-8
    export LC_CTYPE=fr_FR.UTF-8
    export LC_TIME=fr_FR.UTF-8
    export LC_ALL=fr_FR.UTF-8
    export LC_COLLATE=fr_FR.UTF-8
    export LC_NUMERIC=fr_FR.UTF-8
    export HOME=/root

    if [ -n "${PROXY}" ]
    then
        http_proxy="${PROXY}"
        export http_proxy
        https_proxy="${PROXY}"
        export https_proxy
    fi 

    /usr/share/eole/sbin/instance-unattended --store-passwords --file-passwords "${PWD_FILE}" 2>&1 | tee -a "${BOOT_LOG_FILE}"
    exitCode="$?"
    if [[ "$exitCode" -eq 0 ]]
    then
        set +o pipefail
        lgmsg "INSTANCE:DONE:instance OK"
        
        # ici je force l'arret en poweroff de la VM !
        halt -p
        
        exit "$exitCode"
    else
        set +o pipefail
        lgmsg "INSTANCE:ERROR:instance failed"
        exit 1
    fi
fi
exit 0
