#!/bin/bash
#
# Copyright (C) 2026 MOXA Inc. All rights reserved.
# This software is distributed under the terms of the MOXA SOFTWARE NOTICE.
# See the file LICENSE for details.
#
# Authors:
#       2026    Elvis Yao <ElvisCW.Yao@moxa.com>
# Description:
#       Systemd dynamic restore script for Moxa IO states 
#

set -euo pipefail
source "/usr/lib/mx-common-lib"

restore_states() {
        if [[ ! -f "$CONFIG_FILE" ]]; then
                echo "Configuration file $CONFIG_FILE not found. Skipping restore."
                return 0
        fi

        echo "Restoring IO states from $CONFIG_FILE..."

        # Read the file line by line into an array to cleanly preserve all arguments
        while read -r -a cmd_args; do
                # Skip empty lines or comments
                if [[ ${#cmd_args[@]} -eq 0 || "${cmd_args[0]}" == \#* ]]; then
                        continue
                fi

                local tool="${cmd_args[0]}"
                # Dynamically check if the tool exists before running
                if ! command -v "$tool" >/dev/null 2>&1; then
                        echo "Warning: Tool '$tool' not found. Skipping command: ${cmd_args[*]}" >&2
                        continue
                fi

                echo "Executing: ${cmd_args[*]}"

                # Safely execute the array as a literal command with arguments
                if ! "${cmd_args[@]}" >/dev/null 2>&1; then
                        echo "Error: Failed to execute -> ${cmd_args[*]}" >&2
                fi
        done < "$CONFIG_FILE"
        echo "Restore complete."
}

main() {
        restore_states
}

main "$@"
