#!/bin/bash

# exécute une commande dans un conteneur

SSHCMD="ssh -q -i ~/.ssh/eole -o LogLevel=ERROR -o StrictHostKeyChecking=no"
[ "$FORCEPTY" = "yes" ] && SSHCMD="$SSHCMD -t"

commande=$1
container=$2
# ne lancer la commande que si dans un conteneur (ssh)
onlyifcontainer=$3
silent=$4
CMD='eval'

ExecContainer()
{
    ip="$1"
    cmd="$2"
    tcpcheck 2 $ip:22 &>/dev/null || return 1
    $SSHCMD root@$ip "$cmd"
}

if [[ ${container} == "all" ]]
then
    if [[ $(CreoleGet mode_conteneur_actif) == "oui" ]]
    then
        for grp in $(CreoleGet --groups)
        do
          if [[ ${grp} != 'root' ]] && [[ ${grp} != 'all' ]]
          then
              container_ip=$(CreoleGet "container_ip_${grp}")
              if [ ! "$silent" = "yes" ]; then
                  echo "Exécution de la commande [${commande}] dans le conteneur ${grp}"
                  echo
              fi
              ExecContainer "$container_ip" "$commande"
              if [ ! "$silent" = "yes" ]; then
                  echo
              fi
          fi
        done
    fi
else
    if [ -n "$container" ]
    then
        if [ "$container" = 'addc' ]
        then
            container_ip=$(CreoleGet "ad_address" $(CreoleGet "container_ip_addc"))
        else
            container_ip=$(CreoleGet "container_ip_$container")
        fi
    fi
    if [ -n "$container_ip" ] && [ ! "$container_ip" = "127.0.0.1" ]
    then
        ExecContainer "$container_ip" "$commande"
    elif [ "$onlyifcontainer" != "yes" ]
    then
        eval "$commande"
    fi
fi
