#! /bin/sh

# reconnect v1.0
# Try to reconnect quickly to a remote host
# Copyright (c) 2016 Raphaël Halimi <raphael.halimi@gmail.com>

# 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
WAIT=1
SSH_OPTS=""


#
# Functions
#

print_usage () {
  printf "Usage: %s [OPTION]... HOST [ARG]...\n" "$(basename "$0")"
  printf "Try to reconnect quickly to a remote host\n"
  printf "\nOPTIONS:\n"
  print_option "-w WAIT" "Time to wait between tries (in seconds) default is 1"
  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 "\nHOST:\n"
  printf "The host you want to connect to\n"
  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 "w:s:vdh" OPTION ; do
  case $OPTION in
    w) WAIT="$OPTARG" ;;
    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 "WAIT=$WAIT" "SSH_OPTS=$SSH_OPTS"


#
# Checks
#

# Needs at least one argument
[ $# -lt 1 ] && die "Please provide at least one argument"

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

REMOTE_HOST="$1" ; shift
print_debug "REMOTE_HOST=$REMOTE_HOST" "ARGS=$@"


#
# MAIN
#

# Interrupt from keyboard *is* expected
trap - INT

# Main loop
while true ; do

  # Date, syslog-style
  print_verbose "Trying to ping $REMOTE_HOST"
  printf "%s " "$(LANG=C date +"%b %d %T")"
  ping -c 1 "$REMOTE_HOST" > /dev/null 2>&1

  # When host is reachable, connect via ssh
  if [ $? -eq 0 ] ; then
    printf "host %s is up, connecting via ssh\n" "$REMOTE_HOST"
    ssh $SSH_OPTS "$REMOTE_HOST" "$@"
    if [ $? -ne 255 ] ; then
      printf "Press Enter to reconnect, Ctrl-C to exit program." ; read ANSWER
      continue
    fi
  else
    printf "host %s is down, retrying in %is\n" "$REMOTE_HOST" "$WAIT"
  fi

  print_verbose "Sleeping for $WAIT seconds"
  sleep "$WAIT"
done
