#!/bin/bash

# BSD 3-Clause License
# 
# Copyright (c) 2018, alessandrocomodi
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
# 
# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
# 
# * Neither the name of the copyright holder nor the names of its
#   contributors may be used to endorse or promote products derived from
#   this software without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


# Connect to EC2 machine, launch vncserver and connect to it.
# Usage: vnc_ec2 [-g XxY] <ip>
#        vnc_ec2 -k [<ip>]
#   -g: geometry as in -geometry arg of vncserver
#   <ip>: IP address of EC2 instance. If given, it is recorded in .ec2_ip file and can be omitted in future invocations to use the same EC2 instance.
#   -k: kill the running server
# Assumptions:
#   - There must be a private key file ~/.ssh/id_rsa.pem with a corresponding public key on the EC2 instance.
#   - VNC server :7 is used. Any existing :7 server will be killed (if permissions permit). Port 5907 must be open to the EC2 machine.
#   - vncserver must be installed on EC2 instance.
#   - vncviewer must be installed locally.
#   - vnc password must be provided locally in ~/.vnc/passwd


SCRIPT_PATH="${BASH_SOURCE[0]}"
SCRIPT_DIR=`dirname "${SCRIPT_PATH}"`



# Args

GEOMETRY=""
KILL=false
while getopts "g:k" opt
  do
    case "${opt}" in
      g) GEOMETRY=" -geometry ${OPTARG}";;
      k) KILL=true;;
    esac
  done
shift $((OPTIND -1))

IP="$1"
shift



# IP address

if [ "$IP" = "" ]; then
  IP_GIVEN=false
  # Load IP from .ec2_ip
  IP=`cat "$SCRIPT_DIR/.ec2_ip"`
else
  IP_GIVEN=true
fi

# Validate IP
if ! [[ "$IP" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  echo "Error: IP address '$IP' is malformed. Bye."
  exit 1
fi

if [[ $IP_GIVEN = true ]]; then
  # Write IP to .ec2_ip
  echo $IP > "$SCRIPT_DIR/.ec2_ip"
fi



# Kill

if [ "$KILL" = true ]; then
  ssh -i /home/steve/.ssh/id_rsa.pem centos@$IP 'vncserver -kill :7'
  exit
fi



# Do it

# ssh into EC2 instance
echo "Starting new VNC server on :7 (unless already running)."
echo "Kill using \"$0 -k.\""
ssh -i /home/steve/.ssh/id_rsa.pem centos@$IP "vncserver$GEOMETRY :7"

# open local VNC viewer
vncviewer $IP:7 passwd=~/.vnc/passwd &
