source "${BASH_SOURCE%/*}/include/meson64_common.inc"

UBOOT_TARGET_MAP="u-boot-dtb.img;;u-boot.bin.sd.bin:u-boot.bin u-boot.bin:u-boot.nosd.bin u-boot-dtb.img"
CPUMIN=250000
GOVERNOR="ondemand"
BOOTSCRIPT="boot-jethub.cmd:boot.cmd"

if [[ "$BOARD" == "jethubj80" ]]; then
	CPUMAX=1200000
elif [[ "$BOARD" == "jethubj80" ]]; then
	CPUMAX=1416000
fi

uboot_custom_postprocess() {
	if [[ "$BOARD" == "jethubj80" ]]; then
		uboot_gxl_postprocess_ng "$SRC/cache/sources/amlogic-boot-fip/jethub-j80"
	elif [[ "$BOARD" == "jethubj100" ]]; then
		uboot_axg_postprocess_ng "$SRC/cache/sources/amlogic-boot-fip/jethub-j100"
	fi
}

write_uboot_platform() {
	local unable_install_uboot="Unable to install U-Boot."
	local method=0

	if [[ "$2" == *mmcblk* ]]; then
		local mmcblk_prefix
		mmcblk_prefix=$(echo "$2" | grep -Po "mmcblk\d")
		logger "${FUNCNAME[0]}(): mmcblk_prefix = $mmcblk_prefix"

		if [[ -n "$mmcblk_prefix" ]]; then
			local mmc_boot=${mmcblk_prefix}boot
			local of_boot0=/dev/${mmc_boot}0
			local of_boot1=/dev/${mmc_boot}1
			if [[ -e $of_boot0 ]]; then
				method=1
				logger "${FUNCNAME[0]}(): use install in boot emmc partitions"
			fi
		else
			logger "${FUNCNAME[0]}(): mmcblk_prefix is empty. $unable_install_uboot"
			return 1
		fi
	else
		logger "${FUNCNAME[0]}(): use standart u-boot install."
	fi

	dd if="$1/u-boot.bin" of="$2" bs=1 count=442 conv=fsync >/dev/null 2>&1
	dd if="$1/u-boot.bin" of="$2" bs=512 skip=1 seek=1 conv=fsync >/dev/null 2>&1

	if [[ $method == 1 ]]; then
		logger "${FUNCNAME[0]}(): of_boot0 = $of_boot0"
		logger "${FUNCNAME[0]}(): of_boot1 = $of_boot1"

		# unset force-read-only flag
		echo 0 >"/sys/block/${mmc_boot}0/force_ro"
		echo 0 >"/sys/block/${mmc_boot}1/force_ro"
		logger "${FUNCNAME[0]}(): /sys/block/${mmc_boot}0/force_ro value after unsetting read-only flag: $(<"/sys/block/${mmc_boot}0/force_ro")"
		logger "${FUNCNAME[0]}(): /sys/block/${mmc_boot}1/force_ro value after unsetting read-only flag: $(<"/sys/block/${mmc_boot}1/force_ro")"

		local uboot_name=u-boot.bin
		local uboot_size_in_kbytes=$(($(stat --printf "%s" "$1/$uboot_name") / 1024))
		local uboot_offset=1 # 512 bytes in dd
		logger "${FUNCNAME[0]}(): uboot_size_in_kbytes = $uboot_size_in_kbytes"
		logger "${FUNCNAME[0]}(): uboot_offset = $uboot_offset"
		dd if="$1/u-boot.bin" of="$of_boot0" bs=512 skip=1 conv=fsync >/dev/null 2>&1
		dd if="$1/u-boot.bin" of="$of_boot1" bs=512 skip=1 conv=fsync >/dev/null 2>&1
	fi

	logger "${FUNCNAME[0]}(): u-boot successfulley installed"
}

comment_default_rsyslog_rules() {
	local conf_file="$SDCARD/etc/rsyslog.d/50-default.conf"

	if [[ ! -f "${conf_file}" ]]; then
		display_alert "Can't find rsyslog default config at ${conf_file}" "${RELEASE}" "wrn"
		return 2
	fi

	local rule_file_arr=(/var/log/syslog /var/log/auth.log /var/log/kern.log /var/log/mail.log /var/log/mail.err)

	rule_file_escaped_arr=("${rule_file_arr[@]}")
	for ((i = 0; i < ${#rule_file_escaped_arr[*]}; i++)); do
		rule_file_escaped_arr[$i]="${rule_file_arr[$i]//\//\\/}"
	done

	for ((i = 0; i < ${#rule_file_escaped_arr[*]}; i++)); do
		rule_file_escaped="${rule_file_escaped_arr[$i]}"
		regexp="^[^#][^ \t]+[ \t]+.?${rule_file_escaped}.*$"
		if grep -Pq "$regexp" "$conf_file"; then
			sed -i -E -e "s/$regexp/#\0/g" "$conf_file" || {
				echo "sed 's/$regexp/#\0/g' $conf_file failed"
				return 1
			}
		else
			echo "grep '$regexp' $conf_file failed"
			return 2
		fi
	done
}

buildjethomecmds() {
	local toolchain
	# build aarch64 in amd64
	if [[ $(dpkg --print-architecture) == amd64 ]]; then

		toolchain=$(find_toolchain "$UBOOT_COMPILER" "$UBOOT_USE_GCC")
		[[ -z $toolchain ]] && exit_with_error "Could not find required toolchain" "${UBOOT_COMPILER}gcc $UBOOT_USE_GCC"
	fi

	display_alert "Compiler version" "${UBOOT_COMPILER}gcc $(eval env PATH="${toolchain}:${PATH}" "${UBOOT_COMPILER}gcc" -dumpversion)" "info"

	local gpp="${UBOOT_COMPILER}g++"
	local gpp_options="-Os -s -Wall -Wextra -std=c++17 -I$SRC/packages/bsp/jethub"
	local gcc="${UBOOT_COMPILER}gcc"

	env PATH="${toolchain}:${PATH}" "$gpp" $gpp_options "$SRC/packages/bsp/jethub/jethub_get_cmdline_key.cpp" -o "$destination/usr/bin/jethub_get_cmdline_key" || exit_with_error "Unable to compile jethub_get_cmdline_key.cpp"
	env PATH="${toolchain}:${PATH}" "$gpp" $gpp_options "$SRC/packages/bsp/jethub/jethub_get_cmdline_key_cpuid.cpp" -o "$destination/usr/bin/jethub_get_cpuid" || exit_with_error "Unable to compile jethub_get_cmdline_key_cpuid.cpp"

	if [[ $BOARD == jethubj80 ]]; then
		# Bluetooth
		install -m 755 "$SRC/packages/blobs/bt/hciattach/rtk_hciattach_$ARCH" "$destination/usr/bin/rtk_hciattach" || exit_with_error "Unable to install rtk_hciattach"

		cp "$SRC/packages/bsp/jethub/$BOARD/bluetooth/jethub-rtk-hciattach.service" "$destination/lib/systemd/system/" || exit_with_error "Unable to copy jethub-rtk-hciattach.service"

		install -m 755 "$SRC/packages/bsp/jethub/$BOARD/bluetooth/jethub-rtk-hciattach-starter" "$destination/usr/lib/armbian/" || exit_with_error "Unable to install jethub-rtk-hciattach-starter"

		# Board eth led setup
		env PATH="${toolchain}:${PATH}" "$gcc" "$SRC/packages/bsp/jethub/$BOARD/jethub_set_eth_leds.c" -o "$destination/usr/sbin/jethub_set-eth_leds" || exit_with_error "Unable to compile jethub_set_eth_leds.c"
		# Board identifiers
		env PATH="${toolchain}:${PATH}" "$gpp" $gpp_options "$SRC/packages/bsp/jethub/$BOARD/jethub_get_efuse_raw_key.cpp" -o "$destination/usr/bin/jethub_get_efuse_raw_key" || exit_with_error "Unable to compile jethub_get_efuse_raw_key.cpp"
		env PATH="${toolchain}:${PATH}" "$gpp" $gpp_options "$SRC/packages/bsp/jethub/$BOARD/jethub_get_efuse_key_mac.cpp" -o "$destination/usr/bin/jethub_get_mac" || exit_with_error "Unable to compile jethub_get_efuse_key_mac.cpp"
		env PATH="${toolchain}:${PATH}" "$gpp" $gpp_options "$SRC/packages/bsp/jethub/$BOARD/jethub_get_efuse_key_serial.cpp" -o "$destination/usr/bin/jethub_get_serial" || exit_with_error "Unable to compile jethub_get_efuse_key_serial.cpp"
		env PATH="${toolchain}:${PATH}" "$gpp" $gpp_options "$SRC/packages/bsp/jethub/$BOARD/jethub_get_efuse_key_usid.cpp" -o "$destination/usr/bin/jethub_get_usid" || exit_with_error "Unable to compile jethub_get_efuse_key_usid.cpp"
	elif [[ $BOARD == jethubj100 ]]; then
		# Board identifiers
		env PATH="${toolchain}:${PATH}" "$gpp" $gpp_options "$SRC/packages/bsp/jethub/$BOARD/jethub_get_cmdline_key_mac.cpp" -o "$destination/usr/bin/jethub_get_mac" || exit_with_error "Unable to compile jethub_get_cmdline_key_mac.cpp"

		# Wifi & Bluetooth
		mkdir -p --mode=755 "$destination/lib/firmware/" || exit_with_error "Unable to mkdir firmware"
		mkdir --mode=775 "$destination/lib/firmware/brcm/" || exit_with_error "Unable to mkdir brcm"
		cp -P "$SRC"/packages/bsp/jethub/"$BOARD"/{BCM4345C0.hcd,'brcmfmac43455-sdio.jethome,jethub-j100.txt','brcmfmac43455-sdio.jethome,jethub-j100.bin','brcmfmac43456-sdio.jethome,jethub-j100.txt','brcmfmac43456-sdio.jethome,jethub-j100.bin'} "$destination/lib/firmware/brcm/" || exit_with_error "Unable to copy brcm firmware symlinks"

	else
		exit_with_error "Unexpected board \"$BOARD\""
	fi
}

family_tweaks() {
	# Log rotation
	comment_default_rsyslog_rules || display_alert "Unable to comment default rsyslog rules" "${BOARD}" "wrn"

	# Hardware init
	chroot "${SDCARD}" /bin/bash -c "systemctl --no-reload enable jethub-initer.service >/dev/null 2>&1"

	# AR-1098 userland fix for net interface does not up at boot
	chroot "${SDCARD}" /bin/bash -c "systemctl --no-reload enable jethub-ethreset.service >/dev/null 2>&1"

	# pip3 packages
	chroot "${SDCARD}" /bin/bash -c "pip3 install pyserial intelhex python-magic" >>"${DEST}"/debug/install.log 2>&1

	# Hostapd
	chroot "${SDCARD}" /bin/bash -c "systemctl --no-reload disable hostapd.service >/dev/null 2>&1"

	if [[ "$BOARD" == jethubj80 ]]; then
		# Bluetooth
		chroot "${SDCARD}" /bin/bash -c "systemctl --no-reload enable jethub-rtk-hciattach.service >/dev/null 2>&1"
	fi

	display_alert "Adding JetHome repository and authentication key" "/etc/apt/sources.list.d/jethome.list" "info"
	cp "${SRC}"/packages/bsp/jethub/jethome.gpg "${SDCARD}/etc/apt/trusted.gpg.d/"

	echo "deb http://repo.jethome.ru"$([[ $BETA == yes ]] && echo "/beta" )" ${RELEASE} jethome-${RELEASE}" \
		>> "${SDCARD}"/etc/apt/sources.list.d/jethome.list
}

family_tweaks_bsp() {
	# build jethub_get_cmdline_key jethub_get_cpuid
	buildjethomecmds

	# Log rotation
	mkdir -p --mode=755 "$destination/etc/rsyslog.d" || exit_with_error "Unable to mkdir /etc/rsyslog.d"
	cp "$SRC/packages/bsp/jethub/60-jethub-logs-rotate.conf" "$destination/etc/rsyslog.d/" || exit_with_error "Unable to copy 60-jethub-logs-rotate.conf"
	cp "$SRC/packages/bsp/jethub/jethub-remove-log-file.sh" "$destination/usr/lib/armbian/" || exit_with_error "Unable to copy jethub-remove-log-file.sh"

	# Hardware init
	cp "$SRC/packages/bsp/jethub/jethub-initer.service" "$destination/lib/systemd/system/" || exit_with_error "Unable to copy jethub-initer.service"
	cp "$SRC/packages/bsp/jethub/${BOARD}/jethub-init" "$destination/usr/lib/armbian/" || exit_with_error "Unable to copy jethub-init"


	if [[ "$BOARD" == jethubj80 ]]; then
		# AR-1098 userland fix for net interface does not up at boot
		cp "$SRC/packages/bsp/jethub/jethubj80/jethub-ethreset.service" "$destination/lib/systemd/system/" || exit_with_error "Unable to copy jethub-ethreset.service"
		cp "$SRC/packages/bsp/jethub/jethubj80/jethub-ethreset" "$destination/usr/lib/armbian/" || exit_with_error "Unable to copy jethub-ethreset"

		# Ethernet LED setup
		cp "$SRC/packages/bsp/jethub/$BOARD/05-jethub_set_eth_leds.rules" "$destination/etc/udev/rules.d/"
	fi

	mkdir -p "$destination/etc/udev/rules.d"
	mkdir -p "$destination/usr/local/bin"
}