set -eu

export RSYNC_SERVER="screen@rsync.inner.xcastle.net::screen"
export FILE_SERVER='https://file.inner.xcastle.net'
export CONFIG_FILE="/data/global.yaml"

lib::getScreenNum() {
  mkdir -p /data
  local old_config_file="/data/global.conf"

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

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

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() {
  screenNum=$(lib::getScreenNum "$CONFIG_FILE")
  echo 初始化大屏 $screenNum

  echo 安装frp
  install_software frp

  echo 安装rustdesk
  install_software rustdesk

  echo 安装docker
  install_software docker

  # todo flutter && services
  install_software screen
}

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