#!/bin/sh
# Generate bootup wireless config

set -e

TEMPLATE="/lib/wifi/wireless.tmpl"
OUTFILE="${OUTFILE:-/etc/config/wireless}"

if [ -z "$BANDS" ] || [ -z "$OUI" ]; then
    echo "Usage: BANDS=\"2,5,6\" OUI=\"aa:bb:cc\" wireless.sh"
    exit 1
fi

case "$OUI" in
    *[!0-9a-fA-F:]*)
        echo "ERROR: invalid OUI value: $OUI" >&2; exit 1 ;;
esac

: > "$OUTFILE"

bands_list=$(printf '%s' "$BANDS" | tr -d ',' | sed 's/\(.\)/\1 /g')

for BAND in $bands_list; do
    case "$BAND" in
        2|5|6) : ;;
        *) echo "ERROR: unsupported band digit: $BAND" >&2; exit 1 ;;
    esac

    BAND_HEX=$(printf "%02x" "$BAND")
    NEWMAC="${OUI}:00:00:${BAND_HEX}"

    awk -v band="$BAND" \
        -v mac="$NEWMAC" \
    '
    {
        gsub("{{BAND}}", band);
        gsub("{{MAC}}", mac);
        print;
    }
    ' "$TEMPLATE" >> "$OUTFILE"

    echo "" >> "$OUTFILE"
done

echo "Generated wireless config at $OUTFILE:"
cat "$OUTFILE"
