#!/bin/sh
# my_ssh_pubkey
# sshr_port
# sshr_port_len
# sshr_port_base
# tmout
# JUMPER_HOST

SCRIPT_DIR=$(dirname $(realpath $0))
PROJECT_DIR=$(dirname $SCRIPT_DIR)

. $PROJECT_DIR/lib/http.sh
. $PROJECT_DIR/lib/env.sh
. $PROJECT_DIR/lib/email.sh

sshr_ip=$LKP_SERVER
[ -n "$sshr_port" ]      || sshr_port=5051
[ -n "$sshr_port_len" ]  || sshr_port_len=2000
[ -n "$sshr_port_base" ] || sshr_port_base=21000
[ -n "$tmout" ]          || tmout=3600

set_login_tmout()
{
	# set the idle wait time(TMOUT) of linux system, set 0 is prevent timeout exit
	echo "export TMOUT=$tmout" >> /etc/profile
}

set_term()
{
	# $TERM be set "tmux-256color" in tmux, this will raise:
	# 	setterm: tmux-256color: unknown terminal type
	echo "export TERM='linux'" >> /etc/profile
}

generate_key_file()
{
	echo -e "y\n" | ssh-keygen -t rsa -b 2048 -N '' -f /etc/ssh/ssh_host_rsa_key
}

run_ssh()
{
	[ -n "$my_ssh_pubkey" ] || return
	umask 0077
	mkdir -p /root/.ssh/sshr
	echo "$my_ssh_pubkey" >> /root/.ssh/authorized_keys
	if is_docker; then
		generate_key_file
		sshd_path=$(cmd_path sshd)
		$sshd_path -q
	else
		systemctl start sshd
	fi
}

reconnect_every_half_minute()
{
	while true
	do
		ssh -o StrictHostKeyChecking=no -o ExitOnForwardFailure=yes -o TCPKeepAlive=yes \
			-Nf -R $port:localhost:22 sshr@"$sshr_ip" -p "$sshr_port" -i /root/.ssh/sshr/id_rsa &>/dev/null
		sleep 30
	done
}

set_port()
{
	[ -n "$my_ssh_pubkey" ] || return

	chmod 600 /root/.ssh/sshr/id_rsa
	for i in $(seq 1 10)
	do
		port=$(($(date +%s%N)%$sshr_port_len+$sshr_port_base))
		ssh -o StrictHostKeyChecking=no -o ExitOnForwardFailure=yes -o TCPKeepAlive=yes \
			-Nf -R $port:localhost:22 sshr@"$sshr_ip" -p "$sshr_port" -i /root/.ssh/sshr/id_rsa > ssh_msg 2>&1
		[ $? -eq 0 ] && {
			reconnect_every_half_minute &
			return
		}
	done
	ssh_error_message="$(cat -e ssh_msg)"
	echo $ssh_error_message
	port=""
}

mount_user_home()
{
	[[ -n "$secrets_smb_user" ]] || return
	[[ -n "$secrets_smb_pass" ]] || return

	# the mount point in testbox is set the same as its home dir in the account-vm
	[[ -d "/home/$secrets_smb_user" ]] || mkdir -p "/home/$secrets_smb_user"
	mount.cifs //"$JUMPER_HOST"/"$secrets_smb_user" "/home/$secrets_smb_user" \
		   -o username="$secrets_smb_user",password="$secrets_smb_pass"
}

run_email()
{
	deadline=$(date -d "$runtime seconds" +"%Y-%m-%d %H:%M:%S")
	local my_email="$secrets_my_email"

	if [ -n "$port" ]; then
		send_email "borrow_success"
	else
		send_email "borrow_failed"
	fi
}

set_login_tmout
set_term
run_ssh
set_port
report_ssh_info "$port" "${ssh_error_message}"
mount_user_home
run_email
