#!/bin/sh

# Copyright 2015-2020 Rivoreo

# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:

# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE
# FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

if [ $# != 1 ]; then
	printf "Usage: %s <user-name>\\n" "$0" 1>&2
	exit 255
fi
user_name="$1"
if [ "$user_name" = config ] || [ "${user_name#.}" != "$user_name" ] || printf %s "$user_name" | grep -Fq -e "	" -e " " -e \' -e \" -e \# -e \* -e / -e \\ -e :; then
	echo "Invalid user name" 1>&2
	exit 1
fi
if [ -z "$SSH_CLIENT" ]; then
	echo "SSH_CLIENT not set" 1>&2
	exit 1
fi
set -- $SSH_CLIENT
remote_address="$1"
max_valid_time_value=30
max_valid_time_unit=minutes
if [ -f plugins/tsauth/config ] && buffer="`grep -Eo '^MaxValidTime=[0-9]+' plugins/tsauth/config`"; then
	max_valid_time_value=${buffer#MaxValidTime=}
	unset buffer
	if [ $max_valid_time_value -ge 3600 ]; then
		n=$((max_valid_time_value/360))
		max_valid_time_value=${n%?}
		d=${n#$max_valid_time_value}
		[ $d != 0 ] && max_valid_time_value=$max_valid_time_value.$d
		[ $max_valid_time_value = 1 ] && max_valid_time_unit=hour || max_valid_time_unit=hours
		unset n d
	elif [ $max_valid_time_value -ge 60 ]; then
		max_valid_time_value=$((max_valid_time_value/60))
		[ $max_valid_time_value = 1 ] && max_valid_time_unit=minute || max_valid_time_unit=minutes
	else
		[ $max_valid_time_value = 1 ] && max_valid_time_unit=second || max_valid_time_unit=seconds
	fi
fi
set -e
[ -d plugins/tsauth ] || mkdir plugins/tsauth || exit
printf %s\\n "$remote_address" > "plugins/tsauth/$user_name"
printf "You are now authorzied to access our Minecraft server as %s from %s.\\nThis authorization is valid for %s %s.\\n" "$user_name" "$remote_address" "$max_valid_time_value" "$max_valid_time_unit"
sleep 2
