#!/usr/bin/env bash
set -e

action=$1

usage() {
    cat <<-EOF
    usage : $0 action
	availables actions :
	    join    : join the swarm as worker
	    leave   : leave the swarm
	EOF
    exit 0
}

ask_swarm_questions() {
    # General message
    whiptail --title "Swarm Configuration" --msgbox "You will be asked for swarm manager ip address and worker token." 8 78
    # Ask Swarm Manager IP Address
    MANAGER_HOST=$(whiptail --title "Swarm Configuration - Manager IP" --inputbox "Please enter the Swarm Manager IP address: " 8 78 3>&1 1>&2 2>&3)
    # Ask Swarm Worker Token
    WORKER_TOKEN=$(whiptail --title "Swarm Configuration - Worker Token" --inputbox "Please enter the Swarm Worker Token" 8 78 3>&1 1>&2 2>&3)
}

check_if_swarm_connected() {
    set +e
    if docker node ls > /dev/null 2>&1; then
      return 0
    else
      result=$(docker node ls 2>&1)
      if [[ ${result} = *"to connect this node to swarm"* ]]; then
        return 1
      elif [[ ${result} = *"promote the current node to a manager"* ]]; then
        return 2
      fi
    fi
    set -e
}

join_swarm() {
    token=$1
    MANAGER_HOST=$2
    docker swarm join --token ${token} ${MANAGER_HOST}:2377 2>&1
}

leave_swarm() {
    docker swarm leave
}

prejoin_swarm() {
    if ! hostname --fqdn; then
        echo -e "\e[1;31mFQDN not set correctly, please check hostname and /etc/hosts. Exiting...\e[0m"
        exit 1
    fi
    #Swarm check
    check_if_swarm_connected

    swarm_status=$?
    case ${swarm_status} in
      0) echo -e "\e[1;33mThis node is connected to the swarm as manager.\e[0m"
         exit 1 ;;
      1)
         echo -e "\e[1;32mThis node is not connected to the swarm. The configuration will start.\e[0m"

         #Swarm setup
         ask_swarm_questions

         # Logs
         mkdir -p /var/log/xivocc
         chown -R daemon:daemon /var/log/xivocc

         if ! join_swarm ${WORKER_TOKEN} ${MANAGER_HOST} ; then
             echo -e "\e[1;31mUnable to join the swarm. The configuration will exit.\e[0m"
             exit 1
         else
             echo -e "\e[1;33mThis node is connected to the swarm.\e[0m"
             echo -e "\e[1;33mPlease go to XiVO and start orchestration by xivo-orchestration start.\e[0m"
         fi
         ;;
      2)  echo -e "\e[1;33mThis node is already connected to the swarm as worker.\e[0m"
          exit 1 ;;

    esac
}

case ${action} in
    join)    prejoin_swarm;;
    leave)   leave_swarm;;
    *) usage;;
esac

