#!/bin/sh

# SPDX-License-Identifier: ISC
# SPDX-FileCopyrightText: 2025 Thomas Duckworth <tduck@filotimoproject.org>
# SPDX-FileCopyrightText: 2009-2014 Red Hat, Inc.
# SPDX-FileCopyrightText: 2025 Velocity Limitless, LLC.

# See https://gitlab.com/VelocityLimitless/Projects/iw-setregdomain

# Copyright 2009-2014 Red Hat, Inc.  All rights reserved.
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

REGDOMAIN=/etc/iw-regdomain

LOGGER="/usr/bin/logger -t iw-set-regdomain"

getcountry() {
	while read c a z r
	do
		if [ "$z" = "$ZONE" ]
		then
			echo "$c"
			break
		fi
	done < /usr/share/zoneinfo/zone.tab
}

if [ -f "$REGDOMAIN" ]
then
	COUNTRY=$(sed -n 's/^COUNTRY=//p' "$REGDOMAIN" | head -1)
	if [ -n "$COUNTRY" ]
	then
		/usr/bin/iw reg set "$COUNTRY"
		exit
	fi
fi

ZONE=$(timedatectl show -P Timezone 2>/dev/null)

if [ -z "$ZONE" ]
then
	$LOGGER -s "Could not determine timezone. Unable to set wireless regulatory domain."
	exit 1
fi

# Zones with no single associated country
case "$ZONE" in
	UTC|UCT|Universal|Zulu|GMT|GMT[+-]0|GMT0|Greenwich|Factory|posixrules|\
	CET|EET|WET|MET|EST|MST|HST|EST5EDT|CST6CDT|MST7MDT|PST8PDT|\
	Etc/*)
		$LOGGER "Timezone is $ZONE, with no associated country. Not setting wireless regulatory domain."
		exit 0
		;;
esac

COUNTRY=$(getcountry)

# Not in zone.tab: resolve backward-compat aliases (e.g. US/Pacific,
# Asia/Calcutta) to their canonical name and retry. This must not run before
# the direct lookup, as many zone.tab entries are themselves links into
# another country's zone (e.g. Europe/Amsterdam -> Europe/Brussels).
TZDATA_ZI=/usr/share/zoneinfo/tzdata.zi
if [ -z "$COUNTRY" ] && [ -f "$TZDATA_ZI" ]
then
	CANON=$(awk -v z="$ZONE" '$1=="L" && $3==z {print $2; exit}' "$TZDATA_ZI")
	if [ -n "$CANON" ]
	then
		ZONE=$CANON
		COUNTRY=$(getcountry)
	fi
fi

if [ -z "$COUNTRY" ]
then
	$LOGGER -s "Could not determine country for $ZONE. Unable to set wireless regulatory domain."
	exit 1
fi

$LOGGER "Setting regulatory domain to $COUNTRY based on timezone ($ZONE)."
/usr/bin/iw reg set "$COUNTRY"
