#!/bin/sh
set -x
# Reads legacy NET*.b9kvs files and sets up ConnMan accordingly
# This should other ever be ran when NET*b9kvs files exist, and really only
# once ever... this is an artifact of not utilizing ConnMan correctly in
# previous iterations of the firmware.

if [ -e /data/Settings/NET_Eth0AppliedSettings.b9kvs ]; then
  connmanctl enable ethernet
  ethernetSettings=$(/opt/b9creations/B9Creator_SA_KeyValueEditor_IMX8 /data/Settings/NET_Eth0AppliedSettings.b9kvs -L)
  if echo "$ethernetSettings" | grep -iq '.*enabled.*=.*1.*'; then
    ip=$(echo "$ethernetSettings" | grep ip | sed -E 's/.*ip.*=.*"(.*)".*/\1/')
    netmask=$(echo "$ethernetSettings" | grep netmask | sed -E 's/.*netmask.*=.*"(.*)".*/\1/')
    gateway=$(echo "$ethernetSettings" | grep gateway | sed -E 's/.*gateway.*=.*"(.*)".*/\1/')
    nameserver=$(echo "$ethernetSettings" | grep dnsserver | sed -E 's/.*dnsserver.*=.*"(.*),?".*/\1/')
    cat >> /var/lib/connman/legacy.config << EOF
[service_wired]
Type=ethernet
Name=Wired
EOF
    if echo "$ethernetSettings" | grep -iq '.*automode.*=.*0.*'; then
      cat >> /var/lib/connman/legacy.config << EOF
IPv4=$ip/$netmask/$gateway
Nameservers=$nameserver
EOF
    else
      cat >> /var/lib/connman/legacy.config << EOF
IPv4=dhcp
EOF
    fi
  fi
fi

if [ -e /data/Settings/NET_WifiAppliedSettings.b9kvs ]; then
  connmanctl enable wifi
  wifiSettings=$(/opt/b9creations/B9Creator_SA_KeyValueEditor_IMX8 /data/Settings/NET_WifiAppliedSettings.b9kvs -L)
  if echo "$wifiSettings" | grep -iq '.*enabled.*=.*1.*'; then
    name="$(echo "$wifiSettings" | grep essid | sed -E 's/.*essid.*=.*"(.*)".*/\1/')"
    passphrase="$(echo "$wifiSettings" | grep password | sed -E 's/.*password.*=.*"(.*)".*/\1/')"
    ip=$(echo "$wifiSettings" | grep ip | sed -E 's/.*ip.*=.*"(.*)".*/\1/')
    netmask=$(echo "$wifiSettings" | grep netmask | sed -E 's/.*netmask.*=.*"(.*)".*/\1/')
    gateway=$(echo "$wifiSettings" | grep gateway | sed -E 's/.*gateway.*=.*"(.*)".*/\1/')
    cat >> /var/lib/connman/legacy.config << EOF
[service_wifi]
Type=wifi
Name=$name
Passphrase=$passphrase
EOF
    if echo "$wifiSettings" | grep -iq '.*automode.*=.*0.*'; then
      # Nameservers was hardcoded in the leagcy network configuration
      cat >> /var/lib/connman/legacy.config << EOF
IPv4=$ip/$netmask/$gateway
Nameservers=8.8.8.8
EOF
    else
      cat >> /var/lib/connman/legacy.config << EOF
IPv4=dhcp
EOF
    fi
    # Sometimes wifi takes a while to start or won't scan
    sleep 10
  connmanctl scan wifi
  fi
fi


