#! /bin/sh

bcmdir=/etc/bcm.d
speedfile=n3248pxe_uplink_phy_speed.soc

prog=${0##.*/}

[ -e $bcmdir/$speedfile ] || {
    echo "$prog: This command does not apply to this platform" 1>&2
    exit 0
}

# strip out all lines not starting with 49-52, strip legal ganging (treating =/2
# and =/4 as 25 (default), leaving just the speed (or 2 speeds if one pair
# ganged and not the other)in Gb, and# ensuring that we have only a single
# speed, or a single valid pair (if other multiple, we go to the default case
# below). Remove any trailing whitespace, but not leading or embedded.
# Don't need to worry about invalid ganging combinations, update-ports
# and/or the port validator will complain about those, and this script will be
# run again after ports.conf is fixed.
speed=$(sed -r -n -e s,'\s*$,,' -e s,'G$,,' -e 's,=/[24]$,=25,' -e 's,=100G/4$,=25,' \
    -e 's,=50G/2$,=25,' -e 's,=40G/4$,=10,' -e 's,=20G/2$,=10,' \
    -e '/^(49|5[0-2])=/s/^...//p' /etc/cumulus/ports.conf | sort -u)

case "$speed" in
10) xspeed=10000 ;;
25) xspeed=25000 ;;
*)  echo "$prog: Invalid ports.conf for ports 49-52, must all be 10G or 25G" \
     1>&2
     exit 1 ;;
esac

sed "s/\\sspeed=[12][50]000\\s/ speed=$xspeed /" $bcmdir/$speedfile > \
    $bcmdir/tmp-$speedfile
cmp -s $bcmdir/$speedfile $bcmdir/tmp-$speedfile
if [ $? -eq 0 ]; then
    echo "$prog No PHY change required for speed ${speed}Gb"
    rm -f $bcmdir/tmp-$speedfile
    exit 0
fi
mv $bcmdir/tmp-$speedfile $bcmdir/$speedfile || {
    echo "$prog: Failed to modify $bcmdir/$speedfile" 1>&2
    exit 1
}

