#! /bin/sh

# ssh-to v1.0
# Connect to a remote host by typing a single command
# Copyright (c) 2016 Raphaël Halimi <raphael.halimi@gmail.com>
# Idea taken from Rob Flickenger's excellent book "Linux Server Hacks".


# Source shell-script-helper
. /lib/shell-script-helper


#
# Variables
#

# Configuration files
SYSTEM_CONFIG_FILE="/etc/$(basename "$0").conf"
USER_CONFIG_FILE="$HOME/.$(basename "$0").conf"

# Options defaults
SSH_OPTS=""


#
# Functions
#

print_usage () {
  printf "Usage: %s [OPTION]... [ARG]...\n" "$(basename "$0")"
  printf "Connect to a remote host by typing a single command\n"
  printf "\nOPTIONS:\n"
  print_option "-s SSH_OPTS" "Options to pass to ssh, default is empty"
  print_option "-v" "Verbose mode"
  print_option "-d" "Debug mode"
  print_option "-h" "Print this help message"
  printf "\nARGS:\n"
  printf "Any arguments will be passed as-is to the remote host\n"
}


#
# Config files
#

[ -e "$SYSTEM_CONFIG_FILE" ] && . "$SYSTEM_CONFIG_FILE"
[ -e "$USER_CONFIG_FILE" ] && . "$USER_CONFIG_FILE"


#
# Options processing
#

while getopts "s:vdh" OPTION ; do
  case $OPTION in
    s) SSH_OPTS="$OPTARG" ;;
    v) enable_verbose ;;
    d) enable_debug ;;
    h) print_usage ; exit 0 ;;
    *) print_usage ; exit 1 ;;
  esac
done ; shift $((OPTIND-1))
print_debug "SSH_OPTS=$SSH_OPTS"


#
# Checks
#

# This script needs ssh
which ssh > /dev/null || die "Please install ssh"

REMOTE_HOST="$(basename "$0")"
print_debug "REMOTE_HOST=$REMOTE_HOST" "ARGS=$@"

if [ "$REMOTE_HOST" = "ssh-to" ] ; then
  printf "This script is not meant to be called as-is. Create a symlink to it with the\n"
  printf "name of a remote hostname in a directory contained in your path, and run the\n"
  printf "symlink (ex: ln -s %s ~/bin/my-remote-host).\n" "$0"
  die "No remote host to connect to"
fi


#
# MAIN
#

# Simple, really
print_verbose "Trying to connect to remote host $REMOTE_HOST"
ssh $SSH_OPTS "$REMOTE_HOST" "$@"
