set -eu

export RSYNC_SERVER="device@rsync.internal.magicsnap.cn::device"
export FILE_SERVER='https://file.internal.magicsnap.cn'
export CONFIG_FILE="/apps/.data/.global.yaml"

lib::getDeviceNo() {
  mkdir -p /apps/.data

  if [[ -f "$CONFIG_FILE" ]]; then
    deviceNo=$(grep -oP '^\s*deviceNo\s*:\s*"\K[\w\-]+' "$CONFIG_FILE")
  fi
  while [[ ! -n "${deviceNo:-}" ]]; do
    read -p "请输入设备号: " deviceNo
  done

  if [[ ! -f "$CONFIG_FILE" ]]; then
    cat >$CONFIG_FILE <<EOF
deviceNo: "$deviceNo"
EOF
  fi
  echo "$deviceNo"
}

lib::download() {
  local url="$1"
  local dir="$2"
  mkdir -p "$dir"
  curl -L -o "$dir/$(basename "$url")__.download" "$url"
  mv "$dir/$(basename "$url")__.download" "$dir/$(basename "$url")"
}

lib::rsyncDownload() {
  rsync -az --timeout=30 -P "${RSYNC_SERVER}$1" $2
}

install_software() {
  local soft="$1"
  f=/tmp/$soft.sh && wget -q -O $f ${FILE_SERVER}/${soft}/install.sh && source $f && rm $f
}

screen_init() {
  deviceNo=$(lib::getDeviceNo "$CONFIG_FILE")
  echo 初始化大屏 $deviceNo

  echo 安装frp
  install_software frp

  echo 安装rustdesk
  install_software rustdesk

}

case "$1" in
-install)
  if [ -z "$2" ]; then
    echo "请提供要安装的软件名称。"
    exit 1
  fi
  install_software "$2"
  ;;
-init)
  screen_init
  ;;
*)
  echo "用法: {-install 软件名称}"
  exit 1
  ;;
esac
