#!/bin/sh
path="${0%/*}"
. "$path/inc.sh"

# Edit sim1 & sim2 configs, not saved for gws and overwritten by gws setup

usage () {
	die 'gwmodem edit -- [simX]'
}

while : ; do
	case "$1" in
		--)
			shift
			break
		;;
		-*)
			usage
		;;
		*)
			break
		;;
	esac
	shift
done

simx="${1::4}"
shift

generateConf() {
	local simx="$1"

	local APN=
	local PIN=
	local NETWORK=
	local OPERATOR=
	[ -r "/etc/ppp/peers/${simx}.conf" ] && . "/etc/ppp/peers/${simx}.conf"
	
	cat <<- EOL
		${simx}_APN='${APN}'
		${simx}_PIN='${PIN}'
		${simx}_NETWORK='${NETWORK}'
		${simx}_OPERATOR='${OPERATOR}'
	EOL
}

generateCombined() {
	local combinedConf="$1"
	printf "# SIM1\n"   >  "${combinedConf}"
	generateConf sim1   >> "${combinedConf}"
	printf "\n# SIM2\n" >> "${combinedConf}"
	generateConf sim2   >> "${combinedConf}"
}

splitCombined() {
	local combinedConf="$1"
	. "${combinedConf}"

	rm "${sim1conf}" 2>/dev/null
	rm "${sim2conf}" 2>/dev/null

	if [ ! -z "${sim1_APN}" ]; then
		(
			echo "APN='${sim1_APN}'"
			[ -z "${sim1_PIN}"      ] && echo "#PIN='0000'" || echo "PIN='${sim1_PIN}'"
			[ -z "${sim1_NETWORK}"  ] && echo "#NETWORK=25" || echo "NETWORK='${sim1_NETWORK}'"
			[ -z "${sim1_OPERATOR}" ] || echo "OPERATOR='${sim1_OPERATOR}'"
		) > "${sim1conf}"
	fi
	
	if [ ! -z "${sim2_APN}" ]; then
		(
			echo "APN='${sim2_APN}'"
			[ -z "${sim2_PIN}"      ] && echo "#PIN='0000'" || echo "PIN='${sim2_PIN}'"
			[ -z "${sim2_NETWORK}"  ] && echo "#NETWORK=25" || echo "NETWORK='${sim2_NETWORK}'"
			[ -z "${sim2_OPERATOR}" ] || echo "OPERATOR='${sim2_OPERATOR}'"
		) > "${sim2conf}"
	fi
}

run() {
	if [ -z "${simx}" ]; then
		# Edit both sim configs
		local combinedConf="/tmp/xx"
		generateCombined "${combinedConf}"
		if ! editFile "${combinedConf}"; then
			splitCombined "${combinedConf}"
		fi
		rm "${combinedConf}"
	else
		case "${simx}" in
			sim1|sim2) break
			;;
			*) return
		esac
		if [ -e "/etc/ppp/peers/${simx}.conf" ]; then
			# edit existing single sim conf
			editFile "/etc/ppp/peers/${simx}.conf"
		else
			# create new conf
			cat > "/etc/ppp/peers/${simx}.conf" <<- EOL || return
				#APN=
				#PIN=0000
				#NETWORK=25
				#OPERATOR=
			EOL
			editFile "/etc/ppp/peers/${simx}.conf" && rm "/etc/ppp/peers/${simx}.conf"
		fi
	fi
}

run
