#!/usr/bin/env bash
cd $(dirname $0)
source ./lib.sh

set -eu

parsArgs "$@"

# check is root
if [ "$(whoami)" != "root" ]; then
  echo "使用root用户执行当前脚本"
  exit 1
fi

if [ "$DEBUG" = true ]; then
  set -x
fi

# 执行
if [ "$IS_SYNC" = true ]; then
  syncScreen
  echo

  # 过滤--sync参数，防止循环
  filtered_args=()
  for arg in "${args[@]}"; do
      if [[ "$arg" != "--sync" ]]; then
          filtered_args+=("$arg")
      fi
  done

  bash /data/screen/upgrade.sh "${filtered_args[@]}"
  exit
fi

if [[ -z "$CMD" ]]; then
  echo "Error: {cmd} 命令不能为空"
  show_help
fi

if [[ -z "$screenNum" ]]; then
  screenNum=$(getScreenNum)
fi

if [[ -z "$screenNum" ]]; then
  echo "Error: --screenNum 设备码不能为空"
  show_help
fi

trap 'echo -e "\nError occurred on line $LINENO:\n$BASH_COMMAND"; exit 1' ERR

echo '----'
echo "设备码 ${screenNum}"

declare -A systemInfo
detectSystem2 systemInfo

export systemId=${systemInfo['system']}
echo "系统:${systemInfo['system']}, 主机名:${systemInfo['hostname']}"

echo
"cmd_${CMD}" "${CMD_ARGS[@]}"
