#!/usr/bin/env bash
server="192.168.0.254 -i ~/.ssh/rick.epha.se.ed25519"
user="ephase"

# Reutilisons ce que nous avons créé lors du précédent article
source ./message.sh

ssh_sock="/tmp/$(mktemp -u XXXXXXXXXX)"

connect() {
    msg "Create SSH main connection wih socket ${ssh_sock}"
    ssh -N -o ControlMaster=yes -o ControlPath="$ssh_sock" -f ${user}@${server} || {
        error "Can't connect to $server";
        exit 20;
    }
}

launch_command() {
    if [ -z "$1" ]
    then
        error "Launch command require 1 parameter"
        exit 31
    fi
    local command
    command="$1"
    ssh -q -t -S "$ssh_sock" ${user}@${server} "$command" || {
        error "";
        exit 30;
    }
}

cleanup() {
    # close the master control connexion before
    msg "Close SSH main connection"
    ssh -q -o ControlPath="$ssh_sock" -O exit $server || {
        error "Can't close SSH master connection, $ssh_sock remain";
    }
}
connect
trap cleanup EXIT
if [ "$1" = "error" ]
then
    launch_command
fi
for (( i=1; i<=5; i++ ))
do
    launch_command "echo 'Message N°$i from $server'"
    sleep 5
done
