#!/usr/bin/env bash
migrationPath=$1
readonly cachePath="/mnt/cache"
readonly backupPath="${cachePath}/backup"
readonly cacheDev="/dev/mmcblk0p13"

function checkRestoreNeeded()
{
  output=$(setman-restore "geminiCoreAppSettings" version)
  if [ ! -z "${output}" ]; then
    setman-log info "Settings already converted, exiting;"
    exit 0
  fi
}

function mountCache()
{
  mkdir -p ${cachePath}
  mount ${cacheDev} ${cachePath}
  ret=$?
  if [ ${ret} -ne 0 ]; then
    setman-log error "Error mounting ${cacheDev}; exit_code='${ret}'"
    exit ${ret}
  fi
}

function umountCache()
{
  mv ${backupPath} ${cachePath}/backupDone
  umount ${cachePath}
  ret=$?
  if [ ${ret} -ne 0 ]; then
    setman-log error "Error umounting ${cachePath}; exit_code='${ret}'"
    exit ${ret}
  fi

  rm -r ${cachePath}
}

function restoreNetworkSettings()
{
  function maskToCidr() {
    mask=$1
    IFS=.
    octets=($mask)
    cidr=0

    for o in "${octets[@]}"; do
      case $o in
        255) cidr=$((cidr+8));;
        254) cidr=$((cidr+7));;
        252) cidr=$((cidr+6));;
        248) cidr=$((cidr+5));;
        240) cidr=$((cidr+4));;
        224) cidr=$((cidr+3));;
        192) cidr=$((cidr+2));;
        128) cidr=$((cidr+1));;
        0);;
        *) echo "Invalid netmask;"; exit 1;;
      esac
    done

    echo "$cidr"
  }

  settingsDir="${migrationPath}/settings/ipSettings"
  configDir="${backupPath}/config"
  {
    read -r ip0 mask0 gw0
    read -r ip1 mask1 gw1
  } < "${configDir}/gbinterface"

  cidr0=$(maskToCidr "$mask0")
  cidr1=$(maskToCidr "$mask1")

  mode0=$(<${configDir}/gbdhcp)
  mode1=$(<${configDir}/gbdhcpc)

  function checkMode()
  {
    [[ "$1" == "$2" ]] && echo "true" || echo "false"
  }

  mkdir -p ${settingsDir}
  cat > ${settingsDir}/settings.json <<EOF
{
  "version": "1",
  "interfaces": [
    {
      "name": "DEFAULT",
      "enabled": true,
      "ipv4": {
        "dhcp": {
          "enabled": $(checkMode "$mode0" "dhcp"),
          "linklocalFallback": true
        },
        "linklocal": {
          "enabled": false
        },
        "static": {
          "enabled": $(checkMode "$mode0" "static"),
          "ip": "$ip1/$cidr1",
          "gateway": "$gw1"
        }
      }
    },
    {
      "name": "MANAGEMENT",
      "enabled": true,
      "ipv4": {
        "dhcp": {
          "enabled": $(checkMode "$mode1" "dhcp"),
          "linklocalFallback": false
        },
        "linklocal": {
          "enabled": false
        },
        "static": {
          "enabled": $(checkMode "$mode1" "static"),
          "ip": "$ip0/$cidr0",
          "gateway": "$gw0"
        }
      }
    }
  ]
}
EOF

  echo "2" > ${settingsDir}/version.txt
}

function restoreUserData()
{
  settingsDir="${migrationPath}/settings/geminiCoreAppSettings"
  mkdir -p ${settingsDir}

  tar --exclude='timeZone.txt' -czf ${settingsDir}/core.tar.gz -C ${backupPath}/database/core/ .
  echo "1" > ${settingsDir}/version
}

function restoreDeviceIds()
{
  settingsDir="${migrationPath}/settings/deviceIds"
  mkdir -p ${settingsDir}

  cp ${backupPath}/database/devicelabel ${settingsDir}/deviceLabel
  cp ${backupPath}/database/hostname ${settingsDir}/hostname
}

function restoreTimeZone()
{
  timeZoneFile="${backupPath}/database/core/timeZone.txt"

  if [ ! -f "${timeZoneFile}" ]; then
    return
  fi
  timeZone=$(<${timeZoneFile})

  settingsDir="${migrationPath}/settings/timedated-ntp"
  mkdir -p ${settingsDir}

  cat > ${settingsDir}/settings.json <<EOF
{ "datetime": { "TimeZone": "$timeZone" }, "ntp": { "Enabled": true } }
EOF

  cat > ${settingsDir}/timesyncd.conf <<EOF
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it under the
#  terms of the GNU Lesser General Public License as published by the Free
#  Software Foundation; either version 2.1 of the License, or (at your option)
#  any later version.
#
# Entries in this file show the compile time defaults. Local configuration
# should be created by either modifying this file, or by creating "drop-ins" in
# the timesyncd.conf.d/ subdirectory. The latter is generally recommended.
# Defaults can be restored by simply deleting this file and all drop-ins.
#
# See timesyncd.conf(5) for details.

[Time]
NTP=pool.ntp.org
#FallbackNTP=time1.google.com time2.google.com time3.google.com time4.google.com
#RootDistanceMaxSec=5
#PollIntervalMinSec=32
#PollIntervalMaxSec=2048
#SaveIntervalSec=60
EOF
}

function main()
{
  checkRestoreNeeded
  mountCache

  #For extra safety checking inside the /cache folder for the existence of the backup folder
  if [ ! -d ${backupPath} ]; then
    setman-log info "Settings already converted, exiting;"
    umountCache
    exit 0
  fi
  restoreUserData
  restoreNetworkSettings
  restoreDeviceIds
  restoreTimeZone
  umountCache
}

main $@
