#!/bin/bash

# Copyright (C) 2014, 2017, 2019 Multi-Tech Systems

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

MTMODEMS=(LNA3 L4N1)
MODEMS=(LE910-NA1 LE910C4-NF)

function getactivefirmware
{
    /usr/bin/radio-query ${RADIOOPTION} --active-firmware
#   FW=$(/usr/bin/radio-cmd ${RADIOOPTION} 'AT#FWSWITCH?' 2>/dev/null)
#   if (($? != 0)) ; then
#       >&2 echo "FW Query failed"
#       return 1
#   fi
#   [[ $FW =~ \#FWSWITCH:[[:space:]]*([^,]*) ]]
#   echo "${BASH_REMATCH[1]}"
}

# See if string is in array of strings
# parm 1 String
# parm 2 Arrays of strings
function findItem {
    local s check="$1"
    shift
    for s ; do 
        [[ "$s" == "$check" ]] && return 0;
    done
    return 1
}

function usage {
    >&2 echo "$(basename $0) [firmware image SKU]"
    >&2 echo "The firmware image SKU is optional."
    >&2 echo "If not specified, the image SKU will be determined"
    >&2 echo "from the SIM, and automatically switched with the"
    >&2 echo "APN.  Current valid SKU's are 0, 1 and 2"
    exit 1
}

function setchat {
    m=$1
    m=${m,,}
    fw=$2
    silent=$3
    case $fw in
        0)
            ending="non_vz"
            ;;
        1)
            ending="vz"
            ;;
        2)
            # Currently L4N1 only
            ending="non_vz"
            ;;
        *)
            >&2 echo 'Invalid firmware number $fw'
            usage
            exit 1
            ;;
    esac
    source="/etc/ppp/peers/${m}_chat_${ending}"
    target="/etc/ppp/peers/${m}_chat"
    canon_src=$(readlink -f "${source}")
    canon_target=$(readlink -f "${target}")
    if [[ ${canon_src} != ${canon_target} ]] ; then
        if ((silent == 0)) ; then
            echo "Setting chat script to ${source}"
        fi
        ln -sf "${source}" "${target}"
    fi
}

function not_ready {
	>&2 echo "Radio is not ready"
	>&2 echo "Try executing mlinux-switch-apn once the radio is ready"
	exit 1
}

productid=$(/usr/sbin/mts-io-sysfs show product-id)
if [[ $productid =~ [^-]*-([^-]*)- ]] ; then
    mymtmodem="${BASH_REMATCH[1],,}"
else
    >&2 echo "Cannot find the modem in the $productid string"
    exit 1
fi

if ! findItem "${mymtmodem^^}" "${MTMODEMS[@]}"  ; then
  echo "Firmware switch is not supported on ${mymtmodem}."
  usage
  exit 1
fi

if (($# > 0)) ; then
    fw="$1"
    if [[ $fw =~ ^[0-9]+$ ]] ; then
	echo fw is $fw
        if ((fw < 0)) || ((fw > 2)) ; then
            usage
        fi
    else
        >&2 echo "Invalid firmware SKU value"
        usage
    fi
    echo "Switching chat script to firmware SKU $fw"
    setchat $mymtmodem $fw 0
    exit $?
else
    if ! /usr/sbin/mlinux-cell-radio-ready ; then
        >&2 echo Radio is not ready
        >&2 echo Try again later
        exit 1
    fi
    MODEL=$(radio-query ${RADIOOPTION} --model 2>&1)
    result=$?
    if [[ $MODEL =~ [Ee][Rr][Rr][Oo][Rr] ]] ; then
        RADIOOPTION="${RADIOOPTION2}"
        MODEL=$(radio-query ${RADIOOPTION} --model 2>&1)
        result=$?
    fi
    if ((result != 0)) ; then
        >&2echo "No radio on this device."
        usage
        exit 1
    fi
    if ! findItem $MODEL "${MODEMS[@]}" ; then
        >&2 echo "Firmware switch is supported only on ${MODEMS[@]} and this modem is $MODEL"
        usage
    fi
    
    if  fwreply=$(/usr/sbin/mlinux-switch-cell-fw -1); then
        if [[ $fwreply =~ Cellular[[:space:]]+radio[[:space:]]+firmware[[:space:]]+has[[:space:]]+(already[[:space:]]+)*been[[:space:]]+switched[[:space:]]+to[[:space:]]+([^[:space:]]*)[[:space:]]+image\. ]] ; then
          fw=${BASH_REMATCH[2]}
          setchat "${mymtmodem}" $fw 0
        else
	  fw=$(getactivefirmware)
          if (($? == 0)) ; then
              setchat "${mymtmodem}" $fw 0
          fi
      fi
    fi
fi