#!/bin/bash

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

sudo echo "Updating IONT firmware..." | sudo tee -a "$UPDATER_DIR/update.log"


sudo echo "Stopping firmware service" | sudo tee -a "$UPDATER_DIR/update.log"

sudo systemctl stop firmware.service

if [ $? -eq 0 ]; then
    sudo echo "Service stopped" | sudo tee -a "$UPDATER_DIR/update.log"
else
    sudo echo "Failed to stop service" | sudo tee -a "$UPDATER_DIR/update.log"
fi


sudo echo "Copying new firmware files" | sudo tee -a "$UPDATER_DIR/update.log"

sudo cp -r /tmp/update/firmware/* "$FW_DIR"

if [ $? -eq 0 ]; then
    sudo echo "New files copied" | sudo tee -a "$UPDATER_DIR/update.log"
else
    sudo echo "Failed to copy new files" | sudo tee -a "$UPDATER_DIR/update.log"
fi


sudo echo "Starting firmware service" | sudo tee -a "$UPDATER_DIR/update.log"

sudo systemctl restart firmware.service

if [ $? -eq 0 ]; then
    sudo echo "Service restarted" | sudo tee -a "$UPDATER_DIR/update.log"
else
    sudo echo "Failed to restart service" | sudo tee -a "$UPDATER_DIR/update.log"
fi


sudo chown -R iont.tech:iont.tech "$FW_DIR"
sudo chmod +x -R "$FW_DIR"
