#!/bin/sh
# cloonix, container edition: ssh and start, without python.
CLOONFS="/cloonix/cloonfs"
CXP="${CLOONFS}/bin/cloonix-cxp-cli"
CFG="${CLOONFS}/etc/cloonix.cfg"
AWK="${CLOONFS}/bin/awk"

# PROXYSHARE_IN of glob_common.h. It is written out here because sh cannot
# read a C header; if it ever moves, it moves in both places.
PROXYSHARE="/tmp/cloonix_proxymous"

# One field out of the block of one net in the config.
net_field()
{
  ${AWK} -v n="$1" -v k="$2" '
    $1=="CLOONIX_NET:" { inside = ($2==n) }
    inside && $1==k    { print $2; exit }' ${CFG}
}

verb=$1
[ $# -ge 1 ] && shift
case "${verb}" in
  ssh)
    if [ $# -lt 2 ]; then
      echo "usage: cloonix cli <net> ssh <vm> [command]" >&2
      exit 1
    fi
    net=$1; vm=$2; shift 2
    pass=$(net_field ${net} cloonix_passwd)
    if [ -z "${pass}" ]; then
      echo "no net called '${net}' in ${CFG}" >&2
      exit 1
    fi
    # The proxy socket when there is one, the tcp address otherwise. Same
    # test as web_pty.c: a net running in this container is reached through
    # its socket, another one only by its address.
    sock="${PROXYSHARE}_${net}/proxy_pmain.sock"
    if [ -S "${sock}" ]; then
      target=${sock}
    else
      target="$(net_field ${net} cloonix_ip):$(net_field ${net} cloonix_port)"
    fi
    if [ $# -eq 0 ]; then
      CLOONIX_PASSWD=${pass} exec ${CXP} ${target} - ${vm}
    else
      CLOONIX_PASSWD=${pass} exec ${CXP} ${target} - ${vm} "$*"
    fi
    ;;
  start)
    if [ $# -lt 1 ]; then
      echo start wants a net name:
      ${CLOONFS}/bin/grep CLOONIX_NET: ${CFG} | ${AWK} '{print $2}'
      exit 1
    fi
    exec ${CLOONFS}/bin/cloonix-main-server ${CFG} $1
    ;;
  list|stop|cli|add|del|plug|unplug|cnf|dump|sniff|save|rpc|demo|scp|files|trace)
    echo "cloonix ${verb} is not run from inside: the toy is driven from" >&2
    echo "its web gui, given by ./<net>cmd on the host." >&2
    exit 1
    ;;
  *)
    echo "usage: cloonix start <net> | cloonix cli <net> ..." >&2
    exit 1
    ;;
esac
