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

if [[ "$*" == *"--debug"* ]]; then
  set -x
fi

APP_DIR='/data/soft/rustdesk'
ARCH=$(uname -m)
screenNum=$(lib::getScreenNum "$CONFIG_FILE")
echo 当前设备号: $screenNum

needRepairConfig=false

if [[ "$(</etc/machine-id)" = "dcc2e8b826504401bc2ee8b25212ef2b" || "$(</etc/machine-id)" = "29307a4683e84ceb918cca4b80b4427a"  ]]; then
  echo "克隆的系统 重置machine-id"
  echo "" > /etc/machine-id
  echo "" > /var/lib/dbus/machine-id
  systemd-machine-id-setup &> /dev/null
  needRepairConfig=true
fi

mkdir -p $APP_DIR

bin='rustdesk.deb'
if [ "${ARCH}" = 'aarch64' ]; then
  bin="rustdesk-${ARCH}.deb"
fi

echo 下载rustdesk
lib::rsyncDownload /rustdesk/${bin} "${APP_DIR}/"
if [ "${bin}" != 'rustdesk.deb' ]; then
  mv $APP_DIR/$bin $APP_DIR/rustdesk.deb
fi

systemctl stop rustdesk || true
# apt remove -y rustdesk || true

if ! command -v "rustdesk" &>/dev/null; then
  echo 安装rustdesk
  apt install -y $APP_DIR/rustdesk.deb
  systemctl stop rustdesk || true
  needRepairConfig=true
else
  echo rustdesk已安装
fi

if $needRepairConfig; then
  echo 拷贝配置文件
  logged_users=($(who | awk '{print $1}' | sort -u))
  for user in "${logged_users[@]}"; do
    if [ "$user" != "root" ]; then
      mkdir -p "/home/${user}/.config/rustdesk"
      rm "/home/${user}/.config/rustdesk/*.toml" || true
      lib::rsyncDownload /rustdesk/RustDesk2.toml "/home/${user}/.config/rustdesk/RustDesk2.toml"
      chown "${user}:${user}" -R "/home/${user}/.config/rustdesk"
    else
      mkdir -p "/root/.config/rustdesk"
    fi
  done

  rm "/root/.config/rustdesk/*.toml" || true
  lib::rsyncDownload /rustdesk/RustDesk2.toml "/root/.config/rustdesk/RustDesk2.toml"
fi

echo 启动和设置密码
systemctl enable rustdesk
systemctl restart rustdesk
systemctl --no-pager status rustdesk
sudo rustdesk --password txry2025

timeout=10
start_time=$(date +%s) 
while true; do
    if pgrep -f "rustdesk --tray" >/dev/null; then
        echo "rustdesk --tray 已启动"
        break
    fi
    current_time=$(date +%s)
    elapsed=$((current_time - start_time))

    if [ $elapsed -ge $timeout ]; then
        echo "等待rustdesk启动 超时${timeout}秒"
        break
    fi

    echo "等待rustdesk启动 ${elapsed}秒"
    sleep 1
done

sleep 1
sudo rustdesk --password txry2025

remoteId=$(rustdesk --get-id)
echo "远程id: ${remoteId}"

echo 通知服务端绑定
curl --location --request POST 'https://api-magicscreen.xcastle.net/remoteManager/bind' \
--header 'Content-Type: application/json' \
--data-raw '{
    "screenNum" : "'"$screenNum"'",
    "remoteId": "'"$remoteId"'"
}'
echo done

