#!/bin/bash

function showHelp() {
	echo "ssh-proxy [args] command cmd_args"
	echo ""
	echo "args :"
	echo "  --help    Show help"
	echo "command :"
	echo "  status"
	echo "  start profile|port target"
	echo "  stop port"
	echo "  startall"
	echo "  stopall"
	echo "cmd_args :"
	echo "  profile   Name of the profile (~/.config/ssh-proxy/*)"
	echo "  port      Proxy local port (1024-65535)"
	echo "  target    Proxy target [user@]server[:port]"
}

if [ "${1}" == "" ]; then
	showHelp
	exit 1
fi
case ${1} in
	"--help")
		showHelp
		exit 0
	;;
	"status" | "startall" | "stopall");;
	"start" | "stop")
		if [ "${2}" == "" ] || [[ "${2}" == */* ]]; then
			showHelp
			exit 1
		fi
	;;
	*)
		showHelp
		exit 1
	;;
esac

function showProxyStatus() {
	if [ -d /tmp/ssh-proxy-"${USER}" ] && [ "$(find /tmp/ssh-proxy-"${USER}" -maxdepth 0 -empty -exec echo 1 \;)" == "" ]; then
		echo -e "Port\tProxy"
		for FILE in /tmp/ssh-proxy-"${USER}"/*; do
			PORT=$(basename "${FILE}")
			PROXY=$(grep 'PROXY=' "${FILE}" | sed 's/PROXY=//')
			echo -e "${PORT}\t${PROXY}"
		done
	else
		echo "No open proxy"
	fi
}

function startProxy() {
	LOCAL_PORT=0
	PROXY=""

	if [ "${2}" == "" ]; then
		#echo "Use Profile - ${1}"
		#PROFILE_NAME=${1}
		PROFILE_FILE=~/.config/ssh-proxy/${1}
		if [ ! -f "${PROFILE_FILE}" ]; then
			echo "Error: Profile doesn't exist"
			exit 1
		fi
		LOCAL_PORT=$(grep 'PORT=' "${PROFILE_FILE}" | sed 's/PORT=//')
		PROXY=$(grep 'PROXY=' "${PROFILE_FILE}" | sed 's/PROXY=//')
	else
		# echo "Use args - ${1} ${2}"
		LOCAL_PORT="${1}"
		PROXY="${2}"
	fi

	if [[ ! ${LOCAL_PORT} =~ ^[0-9]+$ ]] || [[ ! ${LOCAL_PORT} -lt 65536 ]]; then
		echo "Port is not valid (1024-65535)"
		exit 1
	fi

	PROXY_USER=""
	#PROXY_PASSWORD=""
	PROXY_SERVER=""
	PROXY_SERVER_PORT="22"
	PROXY_ADDRESS=""

	if [[ "${PROXY}" == *@* ]]; then
		PROXY_USER="${PROXY%@*}"
		PROXY_SERVER="${PROXY#*@*}"
	else
		PROXY_SERVER="${PROXY}"
	fi

	#if [[ "${PROXY_USER}" == *:* ]]; then
	#  PROXY_PASSWORD="${PROXY_USER#*:*}"
	#  PROXY_USER="${PROXY_USER%:*}"
	#fi

	if [[ "${PROXY_SERVER}" == *:* ]]; then
		PROXY_SERVER_PORT="${PROXY_SERVER#*:*}"
		PROXY_SERVER="${PROXY_SERVER%:*}"
	fi

	TMP_FILE=/tmp/ssh-proxy-${USER}/${LOCAL_PORT}

	if [ ! -d /tmp/ssh-proxy-"${USER}" ]; then
		mkdir /tmp/ssh-proxy-"${USER}"
	fi

	if [ -f "${TMP_FILE}" ]; then
		echo "Error: tmpFile exist"
		exit 1
	fi

	PROXY_ADDRESS="${PROXY_SERVER}"
	if [ ! "${PROXY_USER}" == "" ]; then
		PROXY_ADDRESS="${PROXY_USER}@${PROXY_SERVER}"
	fi

	echo "Start proxy ${LOCAL_PORT}"
	if ! ssh -fND 127.0.0.1:"${LOCAL_PORT}" "${PROXY_ADDRESS}" -p "${PROXY_SERVER_PORT}"; then
		echo "Error: Proxy start error"
		exit 1
	fi

	PID=$(lsof -i -P | grep ":${LOCAL_PORT} (LISTEN)" | awk -F ' ' '{print $2}')
	if [ "${PID}" == "" ]; then
		echo "Error: No PID found"
		exit 1
	fi
	{
		#if [ ! "${PROFILE_NAME}" == "" ]; then
		#	echo "PROFILE_NAME=${PROFILE_NAME}"
		#fi
		#echo "LOCAL_PORT=${LOCAL_PORT}"
		#echo "PROXY_USER=${PROXY_USER}"
		#echo "PROXY_SERVER=${PROXY_SERVER}"
		#echo "PROXY_SERVER_PORT=${PROXY_SERVER_PORT}"
		echo "PROXY=${PROXY_ADDRESS}"
		echo "PID=${PID}"
	} > "${TMP_FILE}"
}

function stopProxy() {
	LOCAL_PORT=${1}
	TMP_FILE=/tmp/ssh-proxy-${USER}/${LOCAL_PORT}
	if [ ! -f "${TMP_FILE}" ]; then
		echo "Error: tmpFile doesn't exist"
		exit 1
	fi
	echo "Stop proxy ${LOCAL_PORT}"
	PID=$(grep 'PID=' "${TMP_FILE}" | sed 's/PID=//')
	kill "${PID}"
	rm "${TMP_FILE}"
}

function startAll() {
	for FILE in ~/.config/ssh-proxy/*; do
		PROFILE=$(basename "${FILE}")
		startProxy "${PROFILE}"
	done
}

function stopAll() {
	for FILE in /tmp/ssh-proxy-"${USER}"/*; do
		PORT=$(basename "${FILE}")
		stopProxy "${PORT}"
	done
}

case ${1} in
	"status") showProxyStatus;;
	"start") startProxy "${2}" "${3}";;
	"stop") stopProxy "${2}";;
	"startall") startAll;;
	"stopall") stopAll;;
	*) exit 1;;
esac
