#!/bin/bash
# Ensure that the selected country's wifi regulations are respected
# Adapted from quirky/easy version of SNS rc.network, for use by all network managers.
# Returns log entry; exit code = 1 if country code does not match intended within 50 seconds.

#160922 fix so scan can see all channels allowed in my country... 160926
#160926 ###NOTICE### this wait might not be needed, as module knows country code directly.
#200910 resolve shellcheck warnings.

if [ -s /etc/modprobe.d/crdw.conf ] && which crda >/dev/null 2>&1;then #set in quicksetup 170609
    if ! which iw >/dev/null 2>&1 ; then
        echo "${0}: ERROR: iw is missing" >&2
        exit 1
    fi
    CRDW="$(grep '^options cfg80211' /etc/modprobe.d/crdw.conf | cut -f 2 -d '=')" #created by quicksetup
    [ ! "$CRDW" ] && CRDW='00'
    if [ "$CRDW" != "00" ];then
        #at first, did this in /etc/init.d, run 'iw reg set <country>' however, takes up to 40 seconds to set (on odroid xu4).
        #now setting it via a parameter when module cfg80211 loads, which seems to take effect quicker (20 sec on odroid).
        CUR_CRDW="$(iw reg get | grep '^country ' | cut -f 2 -d ' ' | cut -f 1 -d ':')" #ex: AU
        if [ "$CUR_CRDW" = "00" ] || [ "$CUR_CRDW" != "$CRDW" ];then
            crdwCNT=0
            while true; do
                sleep 1
                ((++crdwCNT))
                CUR_CRDW="$(iw reg get | grep '^country ' | cut -f 2 -d ' ' | cut -f 1 -d ':')" #ex: AU
#                echo "crdwCNT=${crdwCNT} CUR_CRDW=${CUR_CRDW}" #for log
                [ "$CUR_CRDW" = "$CRDW" ] && break
                [ "$crdwCNT" -gt 50 ] && exit 1
            done
        fi
    fi
fi
exit 0
