#! /bin/bash


DEVICES_CUSTOM_DIR=${DEVICES_CONFIG_DIR:-/data/custom}
DEVICES_CONFIG_DIR=${DEVICES_CONFIG_DIR:-/data/config}
DEVICES_SEQUENCES_DIR=${DEVICES_SEQUENCES_DIR:-/data/sequences}

DEVICES_CONFIG_FILE=${DEVICES_CONFIG_FILE:-"${DEVICES_CONFIG_DIR}/devices.config"}
DEVICES_USERS_FILE=${DEVICES_USERS_FILE:-"${DEVICES_CONFIG_DIR}/users.tbl"}

DEVICES_LOG_FILE=${DEVICES_LOG_FILE:-/var/log/devices-server.log}

KEEP_TCP_FILE=${KEEP_TCP_FILE:-"${DEVICES_CONFIG_DIR}/keep-tcp-ports"}

main()
{
	mkdir -p "${DEVICES_CUSTOM_DIR}"
	mkdir -p "${DEVICES_CONFIG_DIR}"
	mkdir -p "${DEVICES_SEQUENCES_DIR}"

	if [ ! -f "${DEVICES_CONFIG_FILE}" ]
	then
		create_default_configuration
	fi

	# Flush rules
	/usr/sbin/iptables -F
	/usr/sbin/iptables -X

	# Accept internal communications with loopback.
	/usr/sbin/iptables -A INPUT -i lo -j ACCEPT

	# Accept established connections.
	/usr/sbin/iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

	# Accept allowed services.
	# - SSH:
	iptables -A INPUT -p TCP -m tcp --dport 22 -j ACCEPT
	# - HTTP:
	iptables -A INPUT -p TCP -m tcp --dport 80 -j ACCEPT
	# - HTTPS:
	iptables -A INPUT -p TCP -m tcp --dport 443 -j ACCEPT
	# - Hytem external API:
	iptables -A INPUT -p TCP -m tcp --dport 8080 -j ACCEPT
	# - DHCP Client
	iptables -A INPUT -p UDP -m udp --dport 68 -j ACCEPT
	# - DHCP Server
	iptables -A INPUT -p UDP -m udp --dport 67 -j ACCEPT
	# - PING
	iptables -A INPUT -p icmp -j ACCEPT

	# - Players synchronization
	iptables -A INPUT -p UDP -m udp --dport 2016 -j ACCEPT

	if [ -f "${KEEP_TCP_FILE}" ]
	then
		# Accept Telnet connections on attenuators (legacy API).
		/usr/sbin/iptables -A INPUT -p TCP -m tcp --dport 10000:10512 -j ACCEPT

		# Accept Telnet connections on players API
		/usr/sbin/iptables -A INPUT -p TCP -m tcp --dport 2000 -j ACCEPT
	fi

	# Refuse all other connections
	iptables -A INPUT -j DROP

	while true
	do
		date +"Starting devices server %X at %x"
		/usr/bin/devices-server "${DEVICES_CONFIG_FILE}" 2>&1
		handle_termination_code $?

		sleep 3

	done > "${DEVICES_LOG_FILE}"
}


create_default_configuration()
{
	year=$(date +"%y")
	week=$(date +"%W")
	week=$((week + 1))

	cat > "${DEVICES_CONFIG_FILE}" <<- EOF
Number_of_groups = 1
Devices_per_group = 8
Product_number = 0
Serial_number = ${year}.${week}.000
EOF

	cat > "${DEVICES_USERS_FILE}" <<-EOF
user 0 hytem zCSSO2Ii3Oxao 3 ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
user 1 admin n73qsGXa8rwEs 1 ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
EOF
}


handle_termination_code()
{
	if [ $1 -eq 0 ]; then exit 0; fi
	if [ $1 -eq 20 ]; then /sbin/halt; fi
	if [ $1 -eq 30 ]; then /sbin/reboot; fi
}


main
