#!/bin/sh
export PATH=/opt/lnxall_app/bin:/opt/lnxall_app/sbin:/usr/local/bin:/usr/bin:/usr/sbin:/sbin:/bin

LNXALL_CONFIG=/opt/lnxall_app/app/config
LNXALL_PLATSPEC=/opt/lnxall_app/platspec
TZNAME=America/New_York
US_LOCALE=en_US.UTF-8

# US Eastern time, New York
if command -v timedatectl >/dev/null 2>&1; then
	timedatectl set-timezone "${TZNAME}" || true
fi
if [ -e "/usr/share/zoneinfo/${TZNAME}" ]; then
	ln -sfn "/usr/share/zoneinfo/${TZNAME}" /etc/localtime
fi
printf '%s\n' "${TZNAME}" > /etc/timezone
printf '%s\n' "${TZNAME}" > /etc/TZ

# US English locale
printf 'LANG=%s\nLC_ALL=%s\n' "${US_LOCALE}" "${US_LOCALE}" > /etc/locale.conf
printf 'LANG=%s\nLC_ALL=%s\n' "${US_LOCALE}" "${US_LOCALE}" > /etc/default/locale
if [ -f /etc/locale.gen ]; then
	sed -i 's/^#[[:space:]]*\(en_US.UTF-8[[:space:]]\)/\1/' /etc/locale.gen
	grep -q '^en_US.UTF-8' /etc/locale.gen || printf '%s\n' 'en_US.UTF-8 UTF-8' >> /etc/locale.gen
fi
if command -v locale-gen >/dev/null 2>&1; then
	locale-gen en_US.UTF-8 || locale-gen || true
fi

# version < 0.61.2
if [ $(echo -e "0.61.2\n"$(frpc -v 2>&1) | sort -V | head -n1) != "0.61.2" ] ; then
	# no or empty frpc.ini
	[ ! -s '/etc/frpc.ini' ] && cp -v -f "${LNXALL_CONFIG}/frpc.ini" /etc/frpc.ini

# >= 0.61.2
else
	# overwrite /etc/frpc.toml when it is missing or differs from the packaged file
	if [ -s "${LNXALL_CONFIG}/frpc.toml" ]; then
		if [ ! -s /etc/frpc.toml ] || ! cmp -s "${LNXALL_CONFIG}/frpc.toml" /etc/frpc.toml; then
			cp -v -f "${LNXALL_CONFIG}/frpc.toml" /etc/frpc.toml
		fi
	fi
fi

if cp -v -f "${LNXALL_PLATSPEC}/frpc.service" /usr/lib/systemd/system ; then
	rm -v -f /usr/bin/frpc-sn
	cp -v -f "${LNXALL_PLATSPEC}/frpc-sn.lua" /usr/bin

	systemctl daemon-reload
	systemctl enable frpc
	systemctl restart frpc
fi

exit 0
