#!/bin/sh

if [ $(id -u) -gt 0 ]; then
  echo "This script must be run as root:"
  echo '    curl --compressed -s https://upgrade.wanesy.com/BasicStation_Cockpit | sudo sh'
  exit 1
fi

echo
echo
echo
echo
echo "######                                    ######  ###              ######           "
echo "#....#                                    #%%%%# #%#%#             #%%%%#           "
echo "#....#                                    #%%%%#  ###              #%%%%#           "
echo "#....#                                    #%%%%#                   #%%%%#           "
echo "#....#    #######   ########  ###   #####  #%%%########## #######   #%%%#    #######"
echo "#....#   #.....#   #........# #..###.....# #%%%##%%%%#%%%#%%%%%%%#  #%%%#   #%%%%%# "
echo "#....#  #.....#   #...####...##...........##%%%# #%%%#%%%%%%%%%%%%# #%%%#  #%%%%%#  "
echo "#....# #.....#   #...#    #...##....###....#%%%# #%%%##%%%%%%%%%%%%##%%%# #%%%%%#   "
echo "#.....#.....#    #....####....##...#   #...#%%%# #%%%# #%%%%###%%%%##%%%%#%%%%%#    "
echo "#..........#     #...........# #...#   #####%%%# #%%%# #%%%#   #%%%##%%%%%%%%%#     "
echo "#..........#     #...########  #...#       #%%%# #%%%# #%%%#   #%%%##%%%%%%%%%#     "
echo "#.....#.....#    #....#        #...#       #%%%# #%%%# #%%%#   #%%%##%%%%#%%%%%#    "
echo "#....# #.....#   #.....#       #...#      #%%%%%#%%%%%##%%%#   #%%%#%%%%# #%%%%%#   "
echo "#....#  #.....#  ##.....#####  #...#      #%%%%%#%%%%%##%%%#   #%%%#%%%%#  #%%%%%#  "
echo "#....#   #.....#   #........#  #...#      #%%%%%#%%%%%##%%%#   #%%%#%%%%#   #%%%%%# "
echo "######    #######   #########  #####      ##################   ##########    #######"
echo "                                                                                    "
echo " c  o  m  m  u  n  i  c  a  t  i  o  n       i s       e  v  e  r  y  t  h  i  n  g "
echo "                                                                                    "
echo "                                                                                    "
echo "+----------------------------------------------------------------------------------+"
echo "|                                                                                  |"
echo "|                     Welcome to Wanesy Operational Assistant                      |"
echo "|                          Magic Link auto-configuration                           |"
echo "|                                                                                  |"
echo "+----------------------------------------------------------------------------------+"
echo "                                                                            v4.13.1"
echo
echo
BASE_URL='https://upgrade.wanesy.com/BasicStation_Cockpit'

if [ "${-//[^x]/}" == "x" ]; then
  VERBOSE=1
else
  VERBOSE=0
fi

fail () {
    log "##############################################################################"
    log "#               Error: $@"
    log "##############################################################################"
    log "# ML: https://upgrade.wanesy.com/BasicStation_Cockpit"
    log "# Environment:"
    log "#   > KEROS=${KEROS}"
    log "#   > MULTITECH=${MULTITECH}"
    log "#   > WISTA=${WISTA}"
    log "#   > WIFC=${WIFC}"
    log "#   > LPBS=${LPBS}"
    log "#   > WIIS=${WIIS}"
    log "#   > FEVO=${FEVO}"
    log "#   > ZEPTO=${ZEPTO}"
    log "#   > EUI=${EUI}"
    log "#   > OS_VERSION=${OS_VERSION}"
    log "#   > OS_MAJOR=${OS_MAJOR}"
    log "#   > REGION=${REGION}"
    log "# Gateway software DTO:"
    while read line; do
        log "#   > $line"
    done </tmp/gwswdto.json
    log '#'
    log '##############################################################################'
    log '#   Please contact your support representative                               #'
    log '#----------------------------------------------------------------------------#'
    log '#  /!\ Please include all the logs from the Kerlink logo up to this line.    #'
    log '#  /!\ You may also want to execute `get_logs` and attach the generated file #'
    log '##############################################################################'

    kill $$
    exit 1
}

log () {
    line="ml[$MUTEX_TOKEN]: $@"
    echo "$(date) $line" >&2
    if which systemd-cat &>/dev/null; then
        echo "$line" | systemd-cat -t autoprov
    else
        echo "$line" | logger -t autoprov
    fi

    if [ -d /mnt/sda1 ]; then
        echo "[$(date)] $line" >>/mnt/sda1/magic_link_$(hostname).log
    elif [ -d /mnt/media/sda1 ]; then
        echo "[$(date)] $line" >>/run/media/sda1/magic_link_$(hostname).log
    fi
}

check_tarball() {
  filename="$1"; shift
  if echo "$filename" | grep -q "gz$"; then
    opt="zt"
  else
    opt="t"
  fi
  tar $opt >/dev/null 2>&1 || fail "'$filename' is not a valid tarball"
}

check_ipk() {
  filename="$1"; shift
  files=$(ar t "$filename" 2>/dev/null) || fail "Downloaded file '$filename' for '$name' ($url) isn't a valid IPK file"
  echo "$files" | while read file; do
    case "$file" in
    *.tar|*.tgz|*.tar.gz) ar p "$filename" "$file" | check_tarball "$filename/$file";;
    *) :;;
    esac
  done
}

check_downloaded_file() {
  filename="$1"; shift
  if [ "$filename" == "" ] || [ ! -f "$filename" ]; then
    log "Warning: unable to check downloaded file '$filename'!"
    return 1
  fi

  log "Checking downloaded file: '$filename'"
  case "$filename" in
  *.ipk)
    check_ipk "$filename"
    log "✅ Valid IPK"
    ;;
  *.tar|*.tar.gz|*.tgz)
    cat "$filename" | check_tarball "$filename"
    log "✅ Valid tarball"
    ;;
  *)
    log "Warning: unable to check '$filename' as it is not a tarball or an IPK"
    ;;
  esac
}

download_file () {
    name=$1
    url=$2
    do_not_retry=$3
    if [ "${VERBOSE}" == "1" ]; then
      opt="-v"
    else
      opt="-s"
    fi


    log "Downloading ${name} from ${url}"
    if which systemctl >/dev/null 2>&1; then
        result=$(curl --compressed $opt "${url}" -d @/tmp/gwswdto.json -J -O --retry 99 \
            -w "code=%{http_code}\nfile=%{filename_effective}\ndownloaded=%{size_download}\ndur=%{time_total}\nspeed=%{speed_download}\n" \
            -D /tmp/curl_headers.txt)
    else
        result=$(curl --compressed $opt "${url}" -d @/tmp/gwswdto.json -J -O -C - --retry 99 \
            -w "code=%{http_code}\nfile=%{filename_effective}\ndownloaded=%{size_download}\ndur=%{time_total}\nspeed=%{speed_download}\n" \
            -D /tmp/curl_headers.txt)
    fi
    error=$?

    code="$(echo "$result"        | grep -oE "code=[0-9]{3}"  | awk -F= '{print $2}')"
    filename="$(echo "$result"    | grep -oE "file=.+$"       | awk -F= '{print $2}')"
    duration="$(echo "$result"    | grep -oE "dur=.+$"        | awk -F= '{print $2}')"
    downloaded="$(echo "$result"  | grep -oE "downloaded=.+$" | awk -F= '{print $2}')"
    speed="$(echo "$result"       | grep -oE "speed=[0-9]+"   | awk -F= '{print $2}')"
    expected="$(awk '/Content-Length:/{print $NF}' /tmp/curl_headers.txt)"

    if [ $error -ne 0 ]; then
        if [ "${filename}" == "" ] ; then
            log "Failed to download ${name} from ${url} (curl error: $error) - complete HTTP failure (no headers received)"
            if [ "$do_not_retry" == "" ]; then
                log "Retrying in 10 seconds..."
                sleep 10
                download_file "$name" "$url" "1"
            else
                log "curl failed twice in a row -- give up"
            fi
            return 1;
        fi

        log "Failed to download ${name} from ${url} (curl error: $error) - try again with wget"
        log "Clean up broken download: $(rm -v "$filename")"

        for dl_attempt in $(seq 1 50); do
            wget -c -O "$filename" "${url}"
            wget_error=$?
            downloaded=$(wc -c <"$filename")
            if [ "$downloaded" != "" ] && [ "$expected" != "" ] && [ $downloaded -lt $expected ]; then
                log "Stopped after $downloaded bytes, expected $expected bytes - retrying"
            else
                log "Download finished with wget with $downloaded bytes. Assume HTTP 200 if >0 bytes."
                code="$([ "$downloaded" != "" ] && echo 200 || echo 000)"
                break
            fi
        done

        if [ $wget_error -ne 0 ] || [ $dl_attempt -ge 50 ]; then
            fail "Failed again to download ${name} from ${url} (wget error: $wget_error) - give up"
        fi
    fi

    if [ "$downloaded" != "" ] && [ "$expected" != "" ] && [ $downloaded -lt $expected ]; then
        log "Warning, downloaded $downloaded bytes, expected $expected bytes"
    fi

    case $code in
      200)  log "Downloaded ${name}: ${filename}, $(awk 'BEGIN{printf "%.2f MiB in %.1fs @ %.2f kiB/s", '${downloaded}'/1024/1024, 0.001+'${duration}', '${speed}'/1024}')";;
      204)  log "No local action to perform on this operation, removing temp file: $(rm -v "$filename")";;
        *)  fail "Failed to download ${name} from (HTTP code: $code)";;
    esac

    check_downloaded_file "$filename"
}

download_curl() {
    if curl -V &> /dev/null; then
        log "curl is already on the system"
    else
        log "Installing curl..."
        wget -O /usr/bin/curl 'https://upgrade.wanesy.com/curl'
        chmod +x /usr/bin/curl
    fi

    # Install CA certificates bundle
    if [ ! -f /etc/ssl/certs/ca-certificates.crt ]; then
        log "Installing a CA certificates bundle"
        wget 'https://upgrade.wanesy.com/ca-certificates.crt' -O /etc/ssl/certs/ca-certificates.crt
        chmod 644 /etc/ssl/certs/ca-certificates.crt
    fi
}

[ -d /etc/profile.d ] \
  && [ -n "$(ls -A /etc/profile.d)" ] \
  && for f in /etc/profile.d/*; do
  log "Sourcing $f"
  source $f
done

log "Executing Magic Link: BasicStation_Cockpit"

# Prevent concurrent ML only at bootstrap phase
cleanup() {
  if [ ! -f $MUTEX ]; then
      log "Magic Link finished ($*), though without any mutex lock?!"
  elif [ "$(cat ${MUTEX} 2>&1)" == "${MUTEX_TOKEN}" ]; then
      log "Magic Link finished ($*): $(rm -v ${MUTEX})"
  else
      log "Magic Link finished ($*), not cleaning the other running Magic Link's mutex lock"
      exit 1
  fi
}
klk_trap() {
  fn="$1"; shift
  for s; do trap "$fn $s" "$s"; done
}
MUTEX=/run/ml.lock
MUTEX_TOKEN="$$"
export MUTEX_TOKEN
klk_trap cleanup EXIT INT TERM
if [ -f ${MUTEX} ] && [ "$(cat ${MUTEX})" != "${MUTEX_TOKEN}" ]; then
  log "Another Magic Link (pid $(cat ${MUTEX} 2>&1)) is currently being executed. Please wait for it to finish, or remove ${MUTEX} and try again."
  exit 1
fi
echo ${MUTEX_TOKEN} >${MUTEX}


detect () {
    [ -f /etc/os-release ]  && . /etc/os-release
    [ -f /run/cmdline.env ] && . /run/cmdline.env
    OS_VERSION="$VERSION_ID"

    if grep -q "MultiTech Systems Application Execution Platform with mLinux" /etc/issue; then
        MULTITECH=1
        log "You have a MultiTech AEP gateway"
    else
        case $(hostname) in
        kona-*)
            log "You have a Tektelic gateway"
            TEKTELIC=1
            ;;
        klk-wifc*)
            log "You have a Wirnet iFemtoCell"
            KEROS=1
            WIFC=1
            OS_VERSION=${OS_VERSION:=$(cat /etc/version)}
            ;;

        klk-fevo*)
            log "You have a Wirnet iFemtoCell Evolution"
            KEROS=1
            FEVO=1
            OS_VERSION=${OS_VERSION:=$(cat /etc/version)}
            ;;

        klk-lpbs*)
            log "You have a Wirnet iBTS"
            KEROS=1
            LPBS=1
            OS_VERSION=${OS_VERSION:=$(cat /etc/version)}
            ;;

        klk-wiis*)
            log "You have a Wirnet iStation"
            KEROS=1
            WIIS=1
            OS_VERSION=${OS_VERSION:=$(cat /etc/version)}
            ;;

        klk-ism2*)
            log "You have a Wirnet iStation M2"
            KEROS=1
            WIIS=1
            OS_VERSION=${OS_VERSION:=$(cat /etc/version)}
            ;;

        klk-zeth*)
            log "You have a Wirnet iZeptoCell Ethernet"
            KEROS=1
            ZEPTO=1
            OS_VERSION=${OS_VERSION:=$(cat /etc/version)}
            ;;

        klk-zcel*)
            log "You have a Wirnet iZeptoCell Cellular"
            KEROS=1
            ZEPTO=1
            OS_VERSION=${OS_VERSION:=$(cat /etc/version)}
            ;;

        Wirnet_0*|Wirgrid_0*)
    	    log "You have a Wirnet Station"
            WISTA=1
            fileSystemVersion="$(/usr/local/bin/get_version -u -v | awk -F= '/FILESYSTEM_VER/{print $NF}')"
            if [ "$fileSystemVersion" == "" ]; then
                fileSystemVersion="$(awk -F= '/FILESYSTEM_VER/{print $NF}' /etc/klk-version)"
            fi
            case "${fileSystemVersion}" in
            2011.08-g2d24f64)   OS_VERSION=1.2;;
            2011.08-g5e758a0)   OS_VERSION=2.1;;
            2011.08-gdbb0f32)   OS_VERSION=2.2;;
            2011.08-g7431b51)   OS_VERSION=2.3.3;;
            2011.08-*)          OS_VERSION=2.x;;
            2016.05)            OS_VERSION=3.0;;
            2016.05v1.5)        OS_VERSION=3.1;;
            2016.05v1.9)        OS_VERSION=3.2;;
            2016.05v1.10)       OS_VERSION=3.3;;
            2016.05v1.13)       OS_VERSION=3.6;;
            *)                  OS_VERSION="Unknown wirnet filesystem ($fileSystemVersion)";;
            esac
            ;;

        *)
            python=$(which python || which python3)
            [ -f /etc/init.d/discovery ] && [ ! -f /tmp/board_info.json ] && [ -f /etc/init.d/discovery ] && /etc/init.d/discovery start
            log "You have an unexpected gateway model"
            if [ -f /tmp/sys_startup_status.json ]; then
                KEROS=1

                # detect platform through the python API if available
                platform=$(cat <<EOF | $python
from keroslib import utils
print(utils.getPlatform().strip().replace('-', ''), end="")
EOF
)
                if [ "$platform" != "" ]; then
                  eval "$platform=1"
                  log "Detected platform: $platform"
                fi
                LPBS="$IBTS"
                WIFC="$IFEMTO"
                FEVO="$IFEVO"
                WIIS="$ISTATION"
                ZEPTO="$((IZEPTOE+IZEPTOC))"

                # detect OS version with sys_startup_status.json
                OS_VERSION=$(cat <<EOF | $python
import json
with open('/tmp/sys_startup_status.json') as f:
  print(json.load(f)["cpu"]["sw_version"])
EOF
)
            fi
            OS_VERSION=$(cat /etc/version)
            ;;

        esac

        if [ "$VERSION_ID" != "" ]; then
            OS_VERSION="$VERSION_ID"
        fi

        OS_MAJOR=$(echo "${OS_VERSION}" | awk -F. '{print $1}')

        log "OS version: ${OS_VERSION} (Branch ${OS_MAJOR})"

        if [ "$KEROS" == "1" ]; then
          if [ "$OS_MAJOR" == "1" -o "$OS_MAJOR" == "2" ]; then
            if ! echo "$OS_VERSION" | grep -qE "^[0-9]+\.[0-9]+\.[0-9]+\-spn"; then
              fail "The Magic Link doesn't work with KerOS $OS_VERSION. Please upgrade manually to KerOS 3.x or more recent."
            fi
          fi
        fi
    fi

    EUI=$(get_eui)
    REGION=$(get_region)

    if [ "$(echo -n "${EUI}" | wc -c)" != "16" ]; then
        fail "Invalid EUI"
    fi
    log "EUI: ${EUI}"
}

get_eui_keros () {
    if [ "$LPBS" == "1" ] || [ "$WIFC" == "1" ]; then
      OUI="7276FF"
    else
      OUI="7076FF"
    fi
    if [ -n "$EUI64" ]; then
        echo "${EUI64}"
    else
        awk -F'x|"' '/serial_number": "0x[^"]+",/ {print "'${OUI}'00" toupper($5)}' /tmp/sys_startup_status.json
    fi
}

get_eui () {
    if [ "$MULTITECH" == "1" ]; then
        awk -F'"' '/eui/{gsub(/:/, "", $(NF-1)); print $(NF-1)}' /tmp/ac_data.json
    elif [ "$TEKTELIC" == "1" ]; then
        sqlite3 /tmp/commissioning.db 'select Customer_Gateway_ID from Configuration'
    elif [ "$KEROS" == "1" ]; then
        get_eui_keros
    elif [ "$WISTA" == "1" ]; then
        hostname | awk -F_ '{print "7276FF00" toupper($NF)}'
    else
        fail "get_eui: Unsupported gateway: $(hostname)"
    fi
}

get_region () {
    log "Autodetect gateway region..."
    if [ "$MULTITECH" == "1" ]; then
        awk -F'"' '/productId/{print $(NF-1)}' /tmp/ac_data.json
    elif [ "$TEKTELIC" == "1" ]; then
        sqlite3 /tmp/commissioning.db 'select Operating_Band from Configuration'
    elif [ "$LPBS" == "1" ]; then
        awk -F'"' '/frontend/{f++} f&&/board_serial/{print substr($4,4,2);exit}' /tmp/sys_startup_status.json
    elif [ "$WISTA" == "1" ]; then
        awk -F'"' '/LORABOARD_TYPE/{print $2}' /tmp/loraboard_version
    else
        echo $EUI
    fi
}
keros_get_wmc_hostname() {
  if [ -f /etc/network/connman/openvpn.config ]; then
    awk '/Host/{print "\""$NF"\""; exit}' /etc/network/connman/openvpn.config
  elif [ -f /etc/openvpn/client-openvpn.conf ]; then
    awk '/^remote /{host=$2;ok++}END{if (ok) print "\""host"\""; else print "null"}' /etc/openvpn/client-openvpn.conf 2>/dev/null \
      || echo null
  elif [ -f /etc/openvpn/bscc.conf ]; then
    awk '/^remote /{host=$2;ok++}END{if (ok) print "\""host"\""; else print "null"}' /etc/openvpn/bscc.conf 2>/dev/null \
      || echo null
  else
    awk '/^remote /{host=$2;ok++}END{if (ok) print "\""host"\""; else print "null"}' /etc/openvpn/*.conf 2>/dev/null \
      || echo null
  fi
}

keros_get_security_package() {
  cat /etc/lighttpd.d/keros-fastcgi-webaw.conf 2>/dev/null \
    | tr '"' ' ' \
    | awk '/bin-path/{s=$(NF-1)=="-u"} END{if (s) print "true"; else print "false";}'
}

keros_get_srk_fuses() {
  seq 0 7 \
    | xargs -I{} fslotpreg read SRK{} \
    | xargs -I{} printf %d, {} \
    | sed 's/,\+$//g'
}

keros_get_sb_lock() {
  if grep -q sb_lock /proc/cmdline; then
    grep -oE 'sb_lock=[0-9]+' /proc/cmdline | awk -F= '{print $2}'
  else
    echo "null"
  fi
}

keros_get_board_type() {
    # detect platform through the python API if available
    python=$(which python || which python3)
    platform=$(cat <<EOF | $python 2>/dev/null
from keroslib import utils
print(utils.getPlatform().strip())
EOF
) && [ "$platform" != "" ] && [ "$platform" != "UNKNOWN" ] && echo $platform || { hostname | awk -F- '{print $2}'; }
}

keros_get_packages() {
    if which dpkg >/dev/null 2>&1; then
        dpkg -l | awk '/ker(os|link)/ || /basicstation/{print $2" - "$3}'
        if [ -f /etc/os-release ]; then
            . /etc/os-release
            echo "keros - $VERSION_ID"
        fi
    else
        max=10
        for i in $(seq 1 $max); do
          packages=$(opkg list-installed)
          if [ "$(echo "$packages" | wc -l)" == "0" ]; then
            log "Couldn't get the packages list, try again ($i/$max)"
            sleep 1
            continue
          fi

          # Add keros because it is not set when using a package manager
          keros=$(opkg list-installed keros | awk '{print $NF}')
          [ "$keros" == "" ] && keros=$(cat /etc/version)
          [ "$keros" != "" ] && echo "keros - $keros"

          echo "$packages"
          return 0
        done
    fi
}

get_channels() {
  if grep -q LoRaLocModem /tmp/sys_startup_status.json; then
    echo $((16 * $(grep LoRaLocModem /tmp/sys_startup_status.json | wc -l) ))
  else
    echo 8
  fi
}

keros_format_gwswdto() {
  awk \
   -v "bt=$(keros_get_board_type)" \
   -v "boardRegion=${REGION}" \
   -v "srkFuses=$(keros_get_srk_fuses)" \
   -v "securityPackage=$(keros_get_security_package)" \
   -v "wmcHostName=$(keros_get_wmc_hostname)" \
   -v "init=$(readlink /proc/1/exe)" \
   -v "sbLock=$(keros_get_sb_lock)" \
   -v "channels=$(get_channels)" \
   '    BEGIN {    printf "{\"installedPackages\":{";    }    NR>1 {    printf ",";    }    {    printf "\"" $1 "\":\"" $NF "\"";    }    END {    printf "},";    printf "\"scriptVersion\":\"1.0\",";    printf "\"boardType\":\"" bt "\",";    printf "\"boardRegion\":\"" boardRegion "\",";    printf "\"srkFuses\":[" srkFuses "],";    printf "\"securityPackage\":" securityPackage ",";    printf "\"wmcHostName\":" wmcHostName ",";    printf "\"init\":\"" init "\",";    printf "\"channels\":" channels ",";    printf "\"sbLock\":" sbLock;    printf "}";    }'
}

generic_format_gwswdto() {
  bt="$1"; shift
  awk \
    -v "bt=$bt" \
    -v "boardRegion=${REGION}" \
    '    BEGIN {    printf "{\"installedPackages\":{";    }    NR>1 {    printf ",";    }    {    printf "\"" $1 "\":\"" $NF "\"";    }    END {    printf "},";    printf "\"scriptVersion\":\"1.0\",";    printf "\"boardType\":\"" bt "\",";    printf "\"boardRegion\":\"" boardRegion "\",";    printf "\"srkFuses\":[" srkFuses "],";    printf "\"securityPackage\":" securityPackage ",";    printf "\"wmcHostName\":" wmcHostName ",";    printf "\"init\":\"" init "\",";    printf "\"channels\":" channels ",";    printf "\"sbLock\":" sbLock;    printf "}";    }'
}

wista_format_gwswdto() {
  awk \
    -v "bt=wista" \
    -v "boardRegion=${REGION}" \
    '    /^[^=]+=/ {    gsub(/"/, "", $0);    n = split($0, a, /=/);    sv = a[2];    for (i = 3; i <= n; i++) { sv = sv"="a[i]; }    v[a[1]] = sv;    }    /^....\...\...-..:..:.. -- Dota/ {    sub(/(dota|custo)_/, "", $NF);    sub(/.tar(.gz)?/, "", $NF);    if ($NF ~ /^v[0-9]+\.[0-9]+/) {    n = split($NF, a, /_/);    s = a[2];    for (i = 3; i < n-1; i++) { s = s"_"a[i]; print "a: "i"="a[i];}    v[s] = a[1];    }    else if ($NF ~ /_[0-9]+\.[0-9]+\.[0-9]+/) {    n = split($NF, a, /_/);    s = a[1];    for (i = 2; i <= n; i++) {    if (a[i] ~ /[0-9]+\.[0-9]+\.[0-9]+/) { break; }    s = s"_"a[i];    }    sv=a[i++];    for (; i <= n; i++) { sv = sv"_"a[i]; }    v[s] = sv;    }    else {    v[$NF] = "null";    }    }    END {    printf "{\"installedPackages\":{";    len = 0;    for (i in v) { len++; }    i = 0;    for (s in v) {    sub(/^v/, "", v[s]);    if (v[s] == "null") { sv="null"; }    else { sv="\""v[s]"\""; }    printf "\"%s\":%s", s, sv;    if (++i < len) { printf ","; }    }    printf "},\"scriptVersion\":\"1.0\",\"boardType\":\"wista\",\"boardRegion\":\""boardRegion"\"}";    }'
}

generate_gwswdto() {
    if [ "${KEROS}" == "1" ]; then
        keros_get_packages | keros_format_gwswdto
    elif [ "${MULTITECH}" == "1" ]; then
        opkg list-installed | grep 'kerlink' | generic_format_gwswdto multitech
    elif [ "${TEKTELIC}" == "1" ]; then
        opkg list-installed | grep 'kerlink' | generic_format_gwswdto tektelic
    elif [ "${WISTA}" == "1" ]; then
        /usr/local/bin/get_version -u -v | wista_format_gwswdto
    else
        fail "Unsupported gateway (generate_gwswdto)"
    fi
}

download_curl

KEROS=0
MULTITECH=0
WISTA=0
WIFC=0
LPBS=0
WIIS=0
FEVO=0
ZEPTO=0
EUI=unknown
OS_VERSION=unknown
OS_MAJOR=0
REGION=unknown

log "Detecting current gateway state..."
detect
generate_gwswdto >/tmp/gwswdto.json
log "Gateway DTO: $(cat /tmp/gwswdto.json)"

log "Requesting magic script..."
if [ "${VERBOSE}" == "1" ]; then
  opt="-v"
else
  opt="-s"
fi
curl --compressed $opt -d @/tmp/gwswdto.json "${BASE_URL}/${EUI}" >/tmp/ms || fail "Unable to request magic script"
log "Executing magic script..."
if [ "${VERBOSE}" == "1" ]; then
  sh -x /tmp/ms
else
  sh /tmp/ms
fi
