#!/bin/sh
#
# modemband used to persist the band AT command by overwriting
# network.<iface>.custom_at, which is the user's own list of AT commands: any
# command they had put there was lost, and a 5G selection overwrote the LTE
# one because both shared the single slot.
#
# Bands now live in /etc/atc/pre-activate.d, one file per band family. Move
# whatever the old scheme left inside custom_at over there and hand custom_at
# back to the user.
#

DROPIN_DIR=/etc/atc/pre-activate.d
MIGRATED="$DROPIN_DIR/05-modemband-migrated.at"

changed=0

for iface in $(uci -q show network | sed -n "s/^network\.\([^.]*\)\.proto='atc'\$/\1/p")
do
	values=$(uci -q get "network.${iface}.custom_at") || continue
	[ -n "$values" ] || continue

	# Band commands never contain spaces, so splitting on whitespace is safe
	# for both the list and the plain option form.
	kept=''
	moved=''
	for cmd in $values
	do
		case "$(echo "$cmd" | tr 'a-z' 'A-Z')" in
			AT+GTACT=*|\
			AT+QCFG=\"BAND\",*|\
			AT+QNWPREFCFG=\"*_BAND\"*|\
			AT+CSYSSEL=\"*_BAND\"*)
				moved="$moved$cmd
"
				;;
			*)
				kept="$kept $cmd"
				;;
		esac
	done

	[ -n "$moved" ] || continue

	mkdir -p "$DROPIN_DIR" || continue
	printf '%s' "$moved" >> "$MIGRATED"

	uci -q delete "network.${iface}.custom_at"
	for cmd in $kept
	do
		uci -q add_list "network.${iface}.custom_at=$cmd"
	done
	changed=1
done

[ "$changed" = 1 ] && uci -q commit network

exit 0
