#!/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 x86_64 V3 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_ROCKY10' > "${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_ROCKY10' > "${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
}

# in order for br-lan to work on x86_64/Ubuntu-18.04:
# 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 -t nat -L POSTROUTING | grep -e MASQUERADE | wc -l)"
	[ -z "${masq}" ] && masq=0
	if [ ${masq} -le 2 ] ; then
		# does this have any other side effects?
		# iptables -t nat -A POSTROUTING -o enp1s0        -j MASQUERADE
		# iptables -t nat -A POSTROUTING -o enp0s20f0u7   -j MASQUERADE
		# iptables -t nat -A POSTROUTING -o usb0          -j MASQUERADE
		# iptables -t nat -A POSTROUTING -o modem0        -j MASQUERADE
		: TODO: enable NAT via iptables
	fi
	return 0
}

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

mainfunc() {
	local rval=0

	brlan_setup
	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

	update_wan1lan_mac
	nothup bash -c "sleep 15 ; systemctl disable auditd ; exec netuci"
	return ${retv}
}

mainfunc ; exit $?
