#!/bin/sh

# Created by jiaqiang.ye@lnxall.com
# Lnxall initialization for System
# 2023/06/27

# IMPORTANT: DO NOT CREATE RUNNING PROCESSES WHICH
# CONTINUES TO RUN AFTER THE SCRIPT'S TERMINATION.
# PLEASE DO EXIT SCRIPT WITH ZERO STATUS

# System initialization script for RK3568 aarch64 board

create_sysinfo() {
	local retv=0
	local sysdir='/tmp/sysinfo'

	# create /tmp/sysinfo directory
	mkdir -p -m 0755 ${sysdir} ; retv=$?
	[ $retv -ne 0 ] && return 1

	# write board_name file
	if [ ! -f "${sysdir}/board_name" ] ; then
		echo 'WLOSANY_VM1220T' > "${sysdir}/board_name"
		retv=$?
		chmod 644 "${sysdir}/board_name"
		[ $retv -ne 0 ] && return 2
	fi

	# write model file
	if [ ! -f "${sysdir}/model" ] ; then
		echo 'WLOSANY_VM1220T' > "${sysdir}/model"
		retv=$?
		chmod 644 "${sysdir}/model"
	fi
	return $retv
}

create_dir() {
	local dirp="$1"
	if [ -d "${dirp}" ] ; then
		# already created, just return
		return 0
	fi

	[ -e "${dirp}" ] && rm -rf "${dirp}"
	mkdir -p "${dirp}"
	return $?
}

wait_file() {
	local file="$1"
	local maxcnt="$2"
	local count=0
	while [ ${count} -le ${maxcnt} ] ; do
		if [ -e "${file}" ] ; then
			break
		fi
		echo "Waiting for '${file}': ${count}..."
		sleep 1 ; count=$((count + 1))
	done
	return 0
}

symlink_file() {
	local source="$1"
	local target="$2"

	wait_file "${source}" 3 # wait until file show-up

	local dolink=1
	if [ -e "${target}" ] ; then
		local real="$(readlink -f ${target})"
		[ "${real}" = "${source}" ] && dolink=0
	fi

	if [ ${dolink} -ne 0 ] ; then
		rm -v -rf "${target}"
		ln -s -v -f "${source}" "${target}"
		return $?
	fi
	return 0
}

# setup tty serial device for MOXA arm64 device
setup_ttyserial() {
	rm -rf /dev/ttylnx*
	mx-interface-mgmt serialport | sed -n -r -e 's#^P([0-9]+)\s+/dev/([^ ]+)\s+.+$#/dev/\2 /dev/ttylnx\1#p' | xargs -n 2 ln -sv
	return $?
}

setup_can() {
	map="
can0:lnxcan1;
can1:lnxcan2;
"
	echo "$map" | while IFS= read -r line; do
		[ -z "$line" ] && continue
		#
		old_name=$(echo "$line" | cut -d':' -f1)
		new_name=$(echo "$line" | cut -d':' -f2 | cut -d';' -f1)
		#
		if ip -br link show "$old_name" > /dev/null 2>&1; then
			ip link set $old_name down && ip link set $old_name name $new_name
			if [ $? -ne 0 ]; then
				echo "Failed to rename $old_name to $new_name"
			else
				echo "Successfully renamed $old_name to $new_name"
			fi
		else
			echo "$old_name does not exist"
		fi
	done

	return 0
}


# in order for br-lan to work on RK3568:
# 1, /proc/sys/net/ipv4/ip_forward should be 1;
# 2, NAT should be enabled with iptables.
brlan_setup() {
	if [ "$(cat /proc/sys/net/ipv4/ip_forward)" != "1" ] ; then
		echo 1 > /proc/sys/net/ipv4/ip_forward
	fi

	local masq="$(iptables-legacy -t nat -L POSTROUTING | grep -e MASQUERADE | wc -l)"
	[ -z "${masq}" ] && masq=0
	if [ ${masq} -le 3 ] ; then
		# does this have any other side effects?
		iptables-legacy -t nat -A POSTROUTING -o eth0     -j MASQUERADE
		iptables-legacy -t nat -A POSTROUTING -o eth1     -j MASQUERADE
		iptables-legacy -t nat -A POSTROUTING -o usb0     -j MASQUERADE
		iptables-legacy -t nat -A POSTROUTING -o modem0   -j MASQUERADE
	fi
	return 0
}

update_wan1_mac() {
	local wanmac="$(uci get network.wan.macaddr)"
	[ -z "${wanmac}" ] && wanmac="$(factory get | awk -F= '/MAC=/{print $2}')"
	if [ ${#wanmac} -eq 17 ] ; then
		uci_set_mac wan1 "${wanmac}" 1 && \
			nothup /bin/sh -c 'sleep 6 ; netuci'
	fi
	return 0
}

mainfunc() {
	local rval=0

	sudo mx-interface-mgmt serialport P4 set_interface RS-485-2W
	brlan_setup
	local hostn="$(cat /etc/hostname)"
	[ -n "${hostn}" ] && hostname "${hostn}"

	mkdir -p /var/crash/coredumps
	# update linux kernel coredump pattern
	echo '/var/crash/coredumps/%E-%t-%p-%s.core' > /proc/sys/kernel/core_pattern

	create_dir '/var/run/lnxall' ; rval=$?
	if [ ${rval} -ne 0 ] ; then
		echo "Error, failed to create /var/run/lnxall directory!" 1>&2
		return 1
	fi

	create_sysinfo ; rval=$?
	if [ ${rval} -ne 0 ] ; then
		echo "Error, function has failed: create_info: ${rval}" 1>&2
		return 2
	fi

	setup_can
	setup_ttyserial ; retv=$?
	[ ${rval} -ne 0 ] && return 3

	# mount Solid State Drive if it exists
	update_wan1_mac # error should be ignored
	return 0
}

mainfunc ; exit $?
