#! /bin/bash

while [ -L "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )
  SOURCE=$(readlink "$SOURCE")
  [[ $SOURCE != /* ]] && SOURCE=$DIR/$SOURCE # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )

UPDATER_DIR="/home/iont.tech/updater"

NEW_VERSION="$(sudo cat /tmp/update/version/version | tr -d '\r')"

sudo jq --arg ver "$NEW_VERSION" '.version = $ver' /home/iont.tech/config.json | sudo tee /home/iont.tech/config.json.tmp

if [ $? -eq 0 ]; then
    sudo echo "Version bumped to $NEW_VERSION" | sudo tee -a "$UPDATER_DIR/update.log"
else
    sudo echo "Rewrite version to config failed" | sudo tee -a "$UPDATER_DIR/update.log"
fi


mv /home/iont.tech/config.json.tmp /home/iont.tech/config.json
if [ $? -ne 0 ]; then
    sudo echo "Move version config failed" | sudo tee -a "$UPDATER_DIR/update.log"
fi

if [ -f "/tmp/update/version/swap_zero.sh" ]; then
  SWAP_SH="/tmp/update/version/swap_zero.sh"
else
  SWAP_SH="/tmp/update/version/swap_zero"
fi

"${SWAP_SH}" "/home/iont.tech/config.json"
if [ $? -ne 0 ]; then
    sudo echo "Platform replacement failed" | sudo tee -a "$UPDATER_DIR/update.log"
fi

sudo chown iont.tech:iont.tech /home/iont.tech/config.json
