#!/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

COUNTRY=$(getcountry)

if [ -z "$COUNTRY" ]
then
	case "$ZONE" in
        UTC|UCT|Universal|Zulu|GMT|Etc/UTC|Etc/UCT|Etc/Universal|Etc/Zulu|Etc/GMT)
            $LOGGER "Timezone is $ZONE, with no associated country. Not setting wireless regulatory domain."
            exit 0
            ;;
    esac

    $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"
