#!/bin/bash
# Sipwise NGCP SSH wrapper

set -e

DEBUG=${DEBUG:-false}

if [ -r /etc/default/ngcp-roles ] ; then
  # shellcheck disable=SC1091
  . /etc/default/ngcp-roles
else
  NGCP_SSHD=$(awk '/Port/ { print $2 }' /etc/ssh/sshd_config)
fi

debug () {
  if "$DEBUG" ; then
    echo "[ngcp-ssh]: $*"
  fi
}

usage () {
  printf "Usage: %s [options] <server> [commands]\n" "$0"
}

# defaults
ssh_opts=""
port="${NGCP_SSHD:-22}"
ident="${HOME}/.ssh/id_rsa"

# wrapper opts?
while getopts p:i:o:vt name
do
  case "$name" in
    p) port="$OPTARG";;
    i) ident="$OPTARG";;
    o) ssh_opts+="-o $OPTARG ";;
    v) DEBUG=true; ssh_opts+="-v ";;
    t) ssh_opts+="-t ";;
    ?) usage; exit 0;;
  esac
done
shift $((OPTIND - 1))

if [[ $# -lt 1 ]] ; then
  usage 2>&1
  exit 1
fi

SSH="ssh ${ssh_opts} -p${port} -i ${ident}"
debug "$SSH $*"
$SSH "$@"
