#!/bin/bash
#
# Copyright (c) 2019-2020 P3TERX <https://p3terx.com>
# This is free software, licensed under the MIT License.
# See /LICENSE for more information.
#
# https://github.com/P3TERX/Actions-OpenWrt
# File name: diy-part2.sh
# Description: OpenWrt DIY script part 2 (After Update feeds)
#
# This script performs post-feed-update customizations:
#   - Modifies default IP address and shell
#   - Clones additional package repositories
#   - Creates relative symlinks for custom packages
#   - Patches Luci collections and other package files
#
# Style: Google Shell Style Guide compliant

# ------------------------------------------------------------------------------
# Helper Functions
# ------------------------------------------------------------------------------

# Print a timestamped log message to stderr.
# Arguments:
#   $1 - Log level (e.g., INFO, WARN, ERROR)
#   $2... - Message to print
_log() {
	local level="$1"
	shift
	printf '[%(%Y-%m-%d %H:%M:%S)T] [%s] %s\n' -1 "${level}" "$*" >&2
}

# Clone or pull a Git repository with retry logic.
# Arguments:
#   $1 - Repository URL
#   $2 - Branch name
#   $3 - Additional git clone arguments (e.g., "--depth=1")
#   $4 - Target directory (relative or absolute)
clone_repo() {
	local repo="$1"
	local branch="$2"
	local args="$3"
	local target="$4"
	local attempt

	if [[ -d "${target}" ]]; then
		printf 'Pulling %s at %s...\n' "${repo}" "${target}"
		for attempt in {1..3}; do
			if git -C "${target}" clean -fdx &&
				git -C "${target}" restore . &&
				git -C "${target}" pull; then
				break
			else
				printf 'Pull attempt %d failed, retrying...\n' "${attempt}"
				sleep $((attempt * 2))
			fi
		done
	else
		printf 'Cloning %s %s to %s, using args: %s\n' \
			"${repo}" "${branch}" "${target}" "${args}"
		for attempt in {1..3}; do
			printf 'Clone attempt %d...\n' "${attempt}"
			# Split args and pass to git clone
			if git clone -b "${branch}" $(printf '%s' "${args}" | xargs) "${repo}" "${target}"; then
				break
			else
				printf 'Clone attempt %d failed!\n' "${attempt}"
				sleep $((attempt * 2))
				rm -rf "${target}"
				if [[ "${attempt}" -eq 3 ]]; then
					_log 'ERROR' "Failed to clone ${repo} after 3 attempts."
					exit 1
				fi
			fi
		done
	fi
}

# Compute relative path from one directory to another.
# Pure Bash implementation, no external dependencies.
# Arguments:
#   $1 - Source directory (from)
#   $2 - Target path (to)
# Outputs:
#   Relative path string.
_relpath() {
	local from_dir="$1"
	local to_path="$2"
	local abs_from abs_to

	abs_from="$(cd "${from_dir}" && pwd)" || return 1
	abs_to="$(cd "${to_path}" && pwd)" || return 1

	local from_parts to_parts
	IFS='/' read -ra from_parts <<<"${abs_from}"
	IFS='/' read -ra to_parts <<<"${abs_to}"

	local i=0
	while [[ ${i} -lt ${#from_parts[@]} &&
		${i} -lt ${#to_parts[@]} &&
		"${from_parts[${i}]}" == "${to_parts[${i}]}" ]]; do
		((i++))
	done

	local up_count=$((${#from_parts[@]} - i))
	local rel_path=''
	local j

	for ((j = 0; j < up_count; j++)); do
		rel_path+='../'
	done

	for ((j = i; j < ${#to_parts[@]}; j++)); do
		rel_path+="${to_parts[${j}]}"
		if [[ ${j} -lt $((${#to_parts[@]} - 1)) ]]; then
			rel_path+='/'
		fi
	done

	printf '%s' "${rel_path}"
}

# Create a symlink using a relative path (portable).
# Arguments:
#   $1 - Absolute source path
#   $2 - Target symlink path (to be created)
# Returns:
#   0 on success, 1 on failure.
_create_relative_symlink() {
	local source_abs="$1"
	local target_link="$2"
	local target_dir

	target_dir="$(dirname "${target_link}")"
	mkdir -p "${target_dir}"

	if [[ -L "${target_link}" ]] || [[ -d "${target_link}" ]]; then
		_log 'WARN' "  Removing existing symlink/directory at ${target_link}"
		rm -rf "${target_link}"
	fi

	local rel_target
	rel_target="$(_relpath "${target_dir}" "${source_abs}")"
	if [[ -z "${rel_target}" ]]; then
		_log 'ERROR' "  Failed to compute relative path from ${target_dir} to ${source_abs}"
		return 1
	fi

	if ln -s "${rel_target}" "${target_link}"; then
		_log 'INFO' "  SUCCESS: Created symlink ${target_link} -> ${rel_target}"
		return 0
	else
		_log 'ERROR' "  FAILED: Could not create symlink ${target_link}"
		return 1
	fi
}

# Extract PKG_NAME from a package's Makefile.
# Arguments:
#   $1 - Absolute package directory
# Outputs:
#   PKG_NAME value from Makefile, or empty string if not found.
_extract_pkg_name() {
	local abs_dir="$1"
	local makefile="${abs_dir}/Makefile"
	local pkg_name

	if [[ ! -f "${makefile}" ]]; then
		return 1
	fi

	# Try to extract PKG_NAME from Makefile
	pkg_name="$(grep -E '^\s*PKG_NAME\s*:?=' "${makefile}" | head -1 | sed -E 's/^\s*PKG_NAME\s*:?=\s*(.+)\s*$/\1/')"

	if [[ -z "${pkg_name}" ]]; then
		# Fallback: use directory name if PKG_NAME not found
		pkg_name="$(basename "${abs_dir}")"
	fi

	printf '%s' "${pkg_name}"
}

# Resolve target feed path for a package using fast heuristics or Makefile SECTION.
# Guarantees a two-level path: feeds/<feed>/<subdir>/<pkg_name>
# Arguments:
#   $1 - Absolute package directory
#   $2 - Package name (PKG_NAME from Makefile)
# Outputs:
#   Target symlink path (e.g., feeds/luci/applications/luci-app-xxx)
resolve_target_path() {
	local abs_dir="$1"
	local pkg_name="$2"
	local target_path=''

	# 1. Fast path for LuCI packages (based on name)
	if [[ "${pkg_name}" == luci-app-* ]]; then
		target_path="feeds/luci/applications/${pkg_name}"
		_log 'INFO' '  Fast path: luci-app-* -> applications'
	elif [[ "${pkg_name}" == luci-theme-* ]]; then
		target_path="feeds/luci/themes/${pkg_name}"
		_log 'INFO' '  Fast path: luci-theme-* -> themes'
	elif [[ "${pkg_name}" == luci-lib-* ]]; then
		target_path="feeds/luci/libs/${pkg_name}"
		_log 'INFO' '  Fast path: luci-lib-* -> libs'
	elif [[ "${pkg_name}" == luci-proto-* ]]; then
		target_path="feeds/luci/protocols/${pkg_name}"
		_log 'INFO' '  Fast path: luci-proto-* -> protocols'
	else
		# 2. Extract SECTION from Makefile (first occurrence of SECTION:=...)
		local makefile="${abs_dir}/Makefile"
		local section=''
		if [[ -f "${makefile}" ]]; then
			section="$(grep -E '^\s*SECTION\s*:?=' "${makefile}" | head -1 | sed -E 's/^\s*SECTION\s*:?=\s*([^[:space:]]+).*$/\1/')"
		fi
		_log 'INFO' "  Extracted SECTION from Makefile: '${section}'"

		# 3. Map SECTION to feed and subdirectory (only two levels)
		if [[ -n "${section}" ]]; then
			case "${section}" in
			luci)
				target_path="feeds/luci/applications/${pkg_name}"
				_log 'INFO' "  Mapped SECTION=luci -> feeds/luci/applications"
				;;
			net | network)
				target_path="feeds/packages/net/${pkg_name}"
				_log 'INFO' "  Mapped SECTION=net -> feeds/packages/net"
				;;
			utils | utilities)
				target_path="feeds/packages/utils/${pkg_name}"
				_log 'INFO' "  Mapped SECTION=utils -> feeds/packages/utils"
				;;
			lang | languages)
				target_path="feeds/packages/lang/${pkg_name}"
				_log 'INFO' "  Mapped SECTION=lang -> feeds/packages/lang"
				;;
			libs | libraries)
				target_path="feeds/packages/libs/${pkg_name}"
				_log 'INFO' "  Mapped SECTION=libs -> feeds/packages/libs"
				;;
			admin | administration)
				target_path="feeds/packages/admin/${pkg_name}"
				_log 'INFO' "  Mapped SECTION=admin -> feeds/packages/admin"
				;;
			devel | development)
				target_path="feeds/packages/devel/${pkg_name}"
				_log 'INFO' "  Mapped SECTION=devel -> feeds/packages/devel"
				;;
			multimedia)
				target_path="feeds/packages/multimedia/${pkg_name}"
				_log 'INFO' "  Mapped SECTION=multimedia -> feeds/packages/multimedia"
				;;
			kernel)
				target_path="feeds/packages/kernel/${pkg_name}"
				_log 'INFO' "  Mapped SECTION=kernel -> feeds/packages/kernel"
				;;
			base)
				target_path="feeds/packages/base/${pkg_name}"
				_log 'INFO' "  Mapped SECTION=base -> feeds/packages/base"
				;;
			*)
				_log 'WARN' "  Unknown SECTION '${section}', falling back to name heuristics"
				;;
			esac
		fi

		# 4. Fallback: name-based heuristics (if no valid SECTION or unknown SECTION)
		if [[ -z "${target_path}" ]]; then
			if [[ "${pkg_name}" == net-* ]] || [[ "${pkg_name}" == network-* ]]; then
				target_path="feeds/packages/net/${pkg_name}"
				_log 'INFO' "  Name heuristic: net-* -> feeds/packages/net"
			elif [[ "${pkg_name}" == *-utils ]] || [[ "${pkg_name}" == *-tools ]]; then
				target_path="feeds/packages/utils/${pkg_name}"
				_log 'INFO' "  Name heuristic: *-utils/tools -> feeds/packages/utils"
			elif [[ "${pkg_name}" == lang-* ]]; then
				target_path="feeds/packages/lang/${pkg_name}"
				_log 'INFO' "  Name heuristic: lang-* -> feeds/packages/lang"
			elif [[ "${pkg_name}" == lib* ]] || [[ "${pkg_name}" == *-lib ]]; then
				target_path="feeds/packages/libs/${pkg_name}"
				_log 'INFO' "  Name heuristic: lib* -> feeds/packages/libs"
			else
				# Default fallback: feeds/base
				target_path="feeds/base/${pkg_name}"
				_log 'INFO' "  Default fallback -> feeds/base"
			fi
		fi
	fi

	printf '%s' "${target_path}"
}

# Create symlinks for packages located in a custom directory.
# Scans for Makefiles, caches results, and creates relative symlinks.
# Arguments:
#   $1 - Path to custom packages directory
# Returns:
#   0 on success, 1 if directory does not exist.
create_symlinks() {
	local custom_dir="$1"

	if [[ ! -d "${custom_dir}" ]]; then
		_log 'ERROR' "Custom directory ${custom_dir} does not exist."
		return 1
	fi

	_log 'INFO' "Starting symlink creation for packages in ${custom_dir}"

	# Ensure TOPDIR is set (OpenWrt root)
	if [[ -z "${TOPDIR}" ]]; then
		if [[ -f './rules.mk' ]]; then
			export TOPDIR="${PWD}"
			_log 'INFO' "Auto-detected TOPDIR: ${TOPDIR}"
		elif [[ -f '../rules.mk' ]]; then
			export TOPDIR="${PWD%/*}"
			_log 'INFO' "Auto-detected TOPDIR: ${TOPDIR}"
		else
			_log 'ERROR' 'Cannot find OpenWrt TOPDIR (rules.mk not found).'
			return 1
		fi
	fi

	local cache_file="${custom_dir}/.symlink_cache"
	declare -A cache_map   # auto: rel_path -> "mtime|target"
	declare -A manual_map  # manual: rel_path -> target_path
	declare -A manual_skip # manual: rel_path -> "skip" (if skip flag present)

	# Load existing cache (rel_path is relative to custom_dir)
	if [[ -f "${cache_file}" ]]; then
		_log 'INFO' "Loading cache from ${cache_file}"
		local auto_count=0 manual_count=0
		while IFS='|' read -r rel_path mtime target_path skip_flag; do
			[[ -z "${rel_path}" || "${rel_path}" == \#* ]] && continue

			# Verify that the source directory exists
			if [[ ! -d "${custom_dir}/${rel_path}" ]]; then
				_log 'WARN' "Stale cache entry '${rel_path}' (source missing), skipping."
				continue
			fi

			if [[ "${mtime}" =~ ^[0-9]+$ ]]; then
				cache_map["${rel_path}"]="${mtime}|${target_path}"
				((auto_count++))
			else
				manual_map["${rel_path}"]="${target_path}"
				[[ "${skip_flag}" == "skip" ]] && manual_skip["${rel_path}"]="skip"
				((manual_count++))
			fi
		done <"${cache_file}"
		_log 'INFO' "Loaded ${auto_count} auto + ${manual_count} manual cache entries"
	fi

	local total_packages=0 successful_links=0 failed_links=0
	local cache_hits=0 cache_misses=0

	_log 'INFO' "Scanning for package directories (containing Makefile) under ${custom_dir}..."

	while IFS= read -r dir; do
		[[ "${dir}" == "${custom_dir}" ]] && continue

		((total_packages++))
		local abs_dir
		abs_dir="$(cd "${dir}" && pwd)"

		# Extract PKG_NAME from Makefile, fallback to directory name
		local pkg_name
		pkg_name="$(_extract_pkg_name "${abs_dir}")"
		if [[ -z "${pkg_name}" ]]; then
			pkg_name="$(basename "${dir}")"
		fi

		_log 'INFO' '----------------------------------------'
		_log 'INFO' "Processing package #${total_packages}: ${pkg_name} (directory: $(basename "${dir}"))"
		_log 'INFO' "  Source directory: ${abs_dir}"

		# Compute relative path WITHOUT custom_dir prefix
		local abs_custom_dir
		abs_custom_dir="$(cd "${custom_dir}" && pwd)"
		local rel_path="${abs_dir#${abs_custom_dir}/}"

		local makefile_path="${abs_dir}/Makefile"
		local current_mtime
		current_mtime="$(stat -c %Y "${makefile_path}" 2>/dev/null || printf '0')"

		local target_path=''
		local used_cache=0
		local skip_this=0

		# Check if manually defined (manual entries have precedence)
		if [[ -n "${manual_map[${rel_path}]}" ]]; then
			target_path="${manual_map[${rel_path}]}"
			[[ "${manual_skip[${rel_path}]}" == "skip" ]] && skip_this=1
			_log 'INFO' "  Using manual entry: target='${target_path}', skip=${skip_this}"
			used_cache=1
			((cache_hits++))
		fi

		# If not manual, check auto cache
		if [[ ${used_cache} -eq 0 && -n "${cache_map[${rel_path}]}" ]]; then
			local cached_entry="${cache_map[${rel_path}]}"
			local cached_mtime="${cached_entry%%|*}"
			local cached_target="${cached_entry#*|}"

			if [[ "${cached_mtime}" == "${current_mtime}" ]]; then
				target_path="${cached_target}"
				used_cache=1
				((cache_hits++))
				_log 'INFO' "  Cache hit (mtime ${current_mtime}) -> ${target_path}"
			else
				_log 'INFO' "  Cache stale (mtime changed: ${cached_mtime} -> ${current_mtime})"
				unset "cache_map[${rel_path}]"
			fi
		fi

		# Resolve if not from cache/manual
		if [[ ${used_cache} -eq 0 ]]; then
			((cache_misses++))
			target_path="$(resolve_target_path "${abs_dir}" "${pkg_name}")"
			if [[ -n "${target_path}" ]]; then
				# Do NOT overwrite manual entries
				if [[ -z "${manual_map[${rel_path}]}" ]]; then
					cache_map["${rel_path}"]="${current_mtime}|${target_path}"
					_log 'INFO' "  Cached new entry: ${rel_path} -> ${target_path}"
				fi
			fi
		fi

		if [[ -z "${target_path}" ]]; then
			_log 'ERROR' "  Could not determine target path for ${pkg_name}, skipping."
			((failed_links++))
			continue
		fi

		if [[ ${skip_this} -eq 1 ]]; then
			_log 'INFO' "  Skipping symlink creation due to manual skip flag."
			continue
		fi

		_log 'INFO' "  Target symlink path: ${target_path}"

		if _create_relative_symlink "${abs_dir}" "${target_path}"; then
			((successful_links++))
		else
			((failed_links++))
		fi
	done < <(find "${custom_dir}" -type d \( -name '.git' -o -name 'files' \) -prune -o \
		-type d -exec test -f {}/Makefile \; -print -prune | sort)

	# Process manual entries that were NOT found in the filesystem scan
	# (e.g., directories that don't have a Makefile but are manually defined)
	if [[ ${#manual_map[@]} -gt 0 ]]; then
		_log 'INFO' 'Processing manual-only symlink entries...'
		for rel_path in "${!manual_map[@]}"; do
			# Skip if already processed during scan (they were handled above)
			[[ -f "${custom_dir}/${rel_path}/Makefile" ]] && continue

			local abs_dir="${custom_dir}/${rel_path}"
			local target_path="${manual_map[${rel_path}]}"
			local skip_this=0
			[[ "${manual_skip[${rel_path}]}" == "skip" ]] && skip_this=1

			if [[ ! -d "${abs_dir}" ]]; then
				_log 'WARN' "  Manual entry source directory not found: ${abs_dir}, skipping."
				continue
			fi

			if [[ ${skip_this} -eq 1 ]]; then
				_log 'INFO' "  Manual entry (skip): ${rel_path} -> ${target_path} (skipped)"
				continue
			fi

			_log 'INFO' "  Manual entry: ${rel_path} -> ${target_path}"

			if _create_relative_symlink "${abs_dir}" "${target_path}"; then
				((successful_links++))
			else
				((failed_links++))
			fi
		done
	fi

	# Write updated cache (rel_path is relative to custom_dir)
	{
		printf '# OpenWrt package symlink cache\n'
		printf '# Format: relative_path|mtime|target_path|skip_flag  (mtime=manual for user-defined entries)\n'
		for rel_path in "${!cache_map[@]}"; do
			printf '%s|%s\n' "${rel_path}" "${cache_map[${rel_path}]}"
		done
		for rel_path in "${!manual_map[@]}"; do
			local skip_part=""
			[[ "${manual_skip[${rel_path}]}" == "skip" ]] && skip_part="|skip"
			printf '%s|manual|%s%s\n' "${rel_path}" "${manual_map[${rel_path}]}" "${skip_part}"
		done
	} >"${cache_file}.tmp" && mv "${cache_file}.tmp" "${cache_file}"

	_log 'INFO' "Cache saved with ${#cache_map[@]} auto + ${#manual_map[@]} manual entries"
	_log 'INFO' '========================================'
	_log 'INFO' 'Symlink creation completed.'
	_log 'INFO' "Total packages processed: ${total_packages}"
	_log 'INFO' "Cache hits: ${cache_hits}"
	_log 'INFO' "Cache misses: ${cache_misses}"
	_log 'INFO' "Manual entries processed: ${#manual_map[@]}"
	_log 'INFO' "Successful symlinks: ${successful_links}"
	_log 'INFO' "Failed symlinks: ${failed_links}"
}

# Modify a Luci collection Makefile with given sed expressions.
# Arguments:
#   $1 - Path to Makefile
#   $2... - sed expression arguments (passed directly to sed -i)
modify_luci_collection() {
	local makefile="$1"
	shift
	local sed_exprs=("$@")

	if [[ -f "${makefile}" ]]; then
		printf 'Modifying %s...\n' "${makefile}"
		sed -i "${sed_exprs[@]}" "${makefile}"
	else
		printf 'File %s does not exist.\n' "${makefile}" >&2
	fi
}

# ------------------------------------------------------------------------------
# Main Script
# ------------------------------------------------------------------------------

# Modify default IP address
BASE_FILE_CONFIG='package/base-files/files/bin/config_generate'
if [[ -f "${BASE_FILE_CONFIG}" ]]; then
	sed -i 's/192.168.1.1/192.168.0.1/g' "${BASE_FILE_CONFIG}"
else
	printf 'File %s does not exist.\n' "${BASE_FILE_CONFIG}" >&2
fi

# Modify default shell to bash
PASSWD_FILE='package/base-files/files/etc/passwd'
if [[ -f "${PASSWD_FILE}" ]]; then
	sed -i 's/\/bin\/ash/\/bin\/bash/' "${PASSWD_FILE}"
else
	printf 'File %s does not exist.\n' "${PASSWD_FILE}" >&2
fi

# Clone official and custom package repositories
clone_repo 'https://github.com/anoixa/bpi-r4-pwm-fan' \
	'main' \
	'--depth=1' \
	'custom-packages/bpi-r4-pwm-fan'

clone_repo 'https://github.com/immortalwrt/luci' \
	'master' \
	'--filter=blob:none --sparse --depth=1' \
	'custom-packages/luci'
(
	cd 'custom-packages/luci' || exit 1
	git sparse-checkout set applications/luci-app-dae applications/luci-app-daed
)

clone_repo 'https://github.com/jerrykuku/luci-app-argon-config' \
	'master' \
	'--depth=1' \
	'custom-packages/luci-app-argon-config'

clone_repo 'https://github.com/sirpdboy/luci-app-ddns-go' \
	'main' \
	'--depth=1' \
	'custom-packages/luci-app-ddns-go'

clone_repo 'https://github.com/lisaac/luci-app-diskman' \
	'master' \
	'--depth=1' \
	'custom-packages/luci-app-diskman'

clone_repo 'https://github.com/rockjake/luci-app-fancontrol.git' \
	'main' \
	'--depth=1' \
	'custom-packages/luci-app-fancontrol'

clone_repo 'https://github.com/gdy666/luci-app-lucky.git' \
	'main' \
	'--depth=1' \
	'custom-packages/luci-app-lucky'

clone_repo 'https://github.com/zhanghua000/luci-app-nginx' \
	'master' \
	'--depth=1' \
	'custom-packages/luci-app-nginx'

clone_repo 'https://github.com/zhengmz/luci-app-zerotier' \
	'master' \
	'--depth=1' \
	'custom-packages/luci-app-zerotier'

clone_repo 'https://github.com/jerrykuku/luci-theme-argon.git' \
	'master' \
	'--depth=1' \
	'custom-packages/luci-theme-argon'

clone_repo 'https://github.com/vernesong/OpenClash' \
	'dev' \
	'--depth=1' \
	'custom-packages/openclash'

clone_repo 'https://github.com/immortalwrt/packages' \
	'master' \
	'--filter=blob:none --sparse --depth=1' \
	'custom-packages/packages'
(
	cd 'custom-packages/packages' || exit 1
	git sparse-checkout set lang/golang net/dae net/daed
)

clone_repo 'https://github.com/sbwml/openwrt-qBittorrent' \
	'master' \
	'--depth=1' \
	'custom-packages/qbittorrent'

clone_repo 'https://github.com/sundaqiang/openwrt-packages-backup' \
	'main' \
	'--depth=1' \
	'custom-packages/sundaqiang'

# Create symlinks for all custom packages
create_symlinks 'custom-packages'

# Modify Luci collections to remove uhttpd dependency and adjust themes
modify_luci_collection 'feeds/luci/collections/luci/Makefile' \
	-e '/LUCI_DEPENDS/,/^$/ { /luci-app-attendedsysupgrade/d; s/luci-app-package-manager\s*\\/luci-app-package-manager/g; }'

modify_luci_collection 'feeds/luci/collections/luci-light/Makefile' \
	-e '/LUCI_DEPENDS/,/^$/ { /uhttpd/d; s/luci-theme-bootstrap/luci-theme-argon/g; s/rpcd-mod-rrdns\s*\\/rpcd-mod-rrdns/g; }'

modify_luci_collection 'feeds/luci/collections/luci-nginx/Makefile' \
	-e '/LUCI_DEPENDS/,/^$/ { /luci-app-attendedsysupgrade/d; s/luci-theme-bootstrap/luci-theme-argon/g; }'

modify_luci_collection 'feeds/luci/collections/luci-ssl/Makefile' \
	-e '/LUCI_DEPENDS/,/^$/ { /luci-app-attendedsysupgrade/d; s/luci-app-package-manager\s*\\/luci-app-package-manager/g; }'

modify_luci_collection 'feeds/luci/collections/luci-ssl-openssl/Makefile' \
	-e '/LUCI_DEPENDS/,/^$/ { /luci-app-attendedsysupgrade/d; s/luci-app-package-manager\s*\\/luci-app-package-manager/g; }'

# Modify easyupdate.sh to support Custom OpenWrt firmware format
EASYUPDATE_FILE='custom-packages/sundaqiang/luci/applications/luci-app-easyupdate/root/usr/bin/easyupdate.sh'
if [[ -f "${EASYUPDATE_FILE}" ]]; then
	printf 'Modifying %s...\n' "${EASYUPDATE_FILE}"
	sed -i -E \
		-e '/sysupgrade\s+\$keepconfig\s*\$file/s/sysupgrade/sysupgrade -k/g' \
		-e '/^\s*file/s/\$\{checkShaRet/\/tmp\/\$\{checkShaRet/g' \
		-e '/Check\s+whether\s+EFI\s+firmware/,/^\s*fi/ {
        /^\s+fi/a\    suffix='\''squashfs-sysupgrade.itb'\''
        s/^/#/
      }' \
		-e '/^\s*function\s+checkSha/,/^\s*\}/ {
        s/img\.gz/\itb/
      }' \
		"${EASYUPDATE_FILE}"
else
	printf 'File %s does not exist.\n' "${EASYUPDATE_FILE}" >&2
fi

# Set Rust build to not download CI LLVM (use system LLVM)
RUST_MAKEFILE='feeds/packages/lang/rust/Makefile'
if [[ -f "${RUST_MAKEFILE}" ]]; then
	printf 'Modifying %s...\n' "${RUST_MAKEFILE}"
	sed -i 's/--set=llvm\.download-ci-llvm=true/--set=llvm.download-ci-llvm=false/' "${RUST_MAKEFILE}"
else
	printf 'File %s does not exist.\n' "${RUST_MAKEFILE}" >&2
fi

# Give restore-packages script execution permission
RESTORE_PACKAGES_FILE='files/usr/bin/restore-packages.sh'
if [[ -f "${RESTORE_PACKAGES_FILE}" ]]; then
	printf 'Setting execute permission on %s...\n' "${RESTORE_PACKAGES_FILE}"
	chmod +x "${RESTORE_PACKAGES_FILE}"
else
	printf 'File %s does not exist.\n' "${RESTORE_PACKAGES_FILE}" >&2
fi

# Modify dae version to v1.1.0rc1
DAE_MAKEFILE='custom-packages/packages/net/dae/Makefile'
if [[ -f "${DAE_MAKEFILE}" ]]; then
	printf 'Modifying %s...\n' "${DAE_MAKEFILE}"
	sed -i 's/PKG_VERSION:=.*/PKG_VERSION:=1.1.0_rc1/' "${DAE_MAKEFILE}"
	sed -i 's/PKG_SOURCE:=.*/PKG_SOURCE:=$(PKG_NAME)-1.1.0rc1.zip/' "${DAE_MAKEFILE}"
	sed -i 's#PKG_SOURCE_URL:=.*#PKG_SOURCE_URL:=https://github.com/daeuniverse/dae/releases/download/v1.1.0rc1/dae-full-src.zip?#' "${DAE_MAKEFILE}"
	sed -i 's/PKG_HASH:=.*/PKG_HASH:=726a049813a4d5b800c441ea76ff0ce1846596c180fba0e8ec920a129b3b6e0a/' "${DAE_MAKEFILE}"
else
	printf 'File %s does not exist.\n' "${DAE_MAKEFILE}" >&2
fi
