#!/bin/bash
#
# Author: beyan@beyan.me zhijiezg@cn.ibm.com
# Date: Jan 30 2021
#
#
if [[ "$1" == '' || "$2" == '' || "$3" == '' ]]; then
	echo -e "Usage:"
	echo -e "  $0 [local port to forward] [target address] [target port]"
	echo -e "\nCTRL-C for clear all configured port forwarding."
	exit 127
fi
#

# Config for local port forward
localSSHPort=22
localUser=`echo $USER`

fromPort=$1
targetAddr=$2
targetPort=$3

# Seconds for check the status of port forward
loopTime='30'

# Start SSH Server for localhost
# sudo systemsetup -setremotelogin on
echo -e "Start MacOS ssh service, prepare for your password."
echo -e "\"$USER\" \c"
sudo launchctl start system/sshd

# Find IP address for local enthernet
ipAddrs=`ifconfig | grep -v inet6 | grep inet | awk '{print $2}'`
ifconfig | grep -v inet6 | grep inet | awk '{print $2}'
echo -e "\nEnter '1..n' to choose one: \c"
read index4ip
[[ $index4ip -eq '' ]] && index4ip='2'
locAddr=`echo $ipAddrs | awk '{print $'$index4ip'}'`
echo "IP you choosen: $locAddr"

# Config for SSH login localhost without password
isAuthFilexist=`ls -l ~/.ssh | grep authorized_keys > /dev/null; echo $?`
isPubKeyexist=`ls -l ~/.ssh | grep id_rsa.pub > /dev/null; echo $?`
[[ $isAuthFilexist -eq '0' ]] && echo "SSH authorized file exist: YES"
if [[ $isPubKeyexist -ne '0' ]]; then
	echo "Generate SSH public key."
	ssh-keygen -t rsa -P ''

else
	echo "Public key file exist: YES"
	echo -e "Check if the public key is included in file 'authorized_keys': \c"
	# isKeyinFile=`grep -R "\"\`cat ~/.ssh/id_rsa.pub\`\"" ~/.ssh/authorized_keys > /dev/null; echo $?`
	isKeyinFile=`grep -R "\`cat ~/.ssh/id_rsa.pub\`" ~/.ssh/authorized_keys > /dev/null; echo $?`
	if [[ $isKeyinFile -eq '0' ]]; then
		echo -e "YES"
	else
		cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
		echo -e "FIXED"
	fi
fi


while true
do
# Program for local port $fromPort forward to $targetPort of $targetAddr
# Check if the $fromPort is already used
isPortUsed=`netstat -an | grep $fromPort > /dev/null; echo $?`
if [[ $isPortUsed -ne '0' ]]; then
	echo "$fromPort is not used, start port forward"
	ssh -fNn -L $locAddr:$fromPort:$targetAddr:$targetPort $localUser@127.0.0.1 -p $localSSHPort
	if [[ $? -eq '0' ]]; then
		echo -e "\nPort: $fromPort forward done!"
		prompt='y'
	else
		echo "Port forward failed!! Waiting for next loop!!"
	fi
else
	echo -e "\nPort: $fromPort already used!"
	if [[ $prompt != 'y' ]]; then
		echo -e "\nCheck port forwarding status only, \c"
		echo -e "Enter 'y', Or other key to exit: \c"
		read prompt
		[[ $prompt != 'y' ]] && exit 128
	fi
fi

# Show connection via port forwarded.
echo -e "-----------------------"
echo -e "Connected host: "
netstat -an | grep $fromPort | grep -v "*.*" | awk '{print $5}'

# End of port forward
#

# trap 'continue' SIGINT
trap 'break' SIGINT
sleep $loopTime

done

echo -e "\n\nStop SSH Service: \c" 
# sudo systemsetup -setremotelogin off
sudo launchctl stop system/sshd
echo -e "OK"
echo -e "\nClear all configured port forwarding: \c"
killall ssh
echo -e "OK"
echo -e "\nStart SSH Service: \c"
# sudo systemsetup -setremotelogin on
sudo launchctl start system/sshd
echo -e "OK"

exit 0
