#!/bin/bash

WEB_SERVER_DIR="/home/iont.tech/admin/server"
UPDATER_DIR="/home/iont.tech/updater"

sudo mkdir -p "$WEB_SERVER_DIR"

sudo echo "Updating admin server..." | sudo tee -a "$UPDATER_DIR/update.log"


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

sudo systemctl stop admin-server.service

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


sudo echo "Removing old admin server files" | sudo tee -a "$UPDATER_DIR/update.log"

sudo rm -rf "$WEB_SERVER_DIR"/*

if [ $? -eq 0 ]; then
    sudo echo "Old admin server files removed" | sudo tee -a "$UPDATER_DIR/update.log"
else
    sudo echo "Failed to remove old admin server files" | sudo tee -a "$UPDATER_DIR/update.log"
fi


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

sudo cp -r /tmp/update/admin-server/* "$WEB_SERVER_DIR"

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


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

sudo systemctl restart admin-server.service

if [ $? -eq 0 ]; then
    sudo echo "Service started" | sudo tee -a "$UPDATER_DIR/update.log"
else
    sudo echo "Service failed to start" | sudo tee -a "$UPDATER_DIR/update.log"
fi


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