#!/bin/bash

set -e

ARCH=""
TTMANAGER_WORK_DIR="$(pwd)"
TTMANAGER_NAME="tt_installer"
TTMANAGER_EXE="$TTMANAGER_WORK_DIR/$TTMANAGER_NAME"
case $(uname -m) in
    "armv7l")
        ARCH="arm32"
        ;;
    "aarch64")
        ARCH="arm64"
        ;;
    "x86_64")
        ARCH="amd64"
        ;;
    *)
        echo "不支持的系统架构: $ARCH"
        exit 1
        ;;
esac

sh_c='sh -c'
user="$(id -un 2>/dev/null || true)"
sh_c='sh -c'
if [ "$user" != 'root' ]; then
  if command_exists sudo; then
    sh_c='sudo -E sh -c'
  elif command_exists su; then
    sh_c='su -c'
  else
    cat >&2 <<-'EOF'
			Error: this installer needs the ability to run commands as root.
			We are unable to find either "sudo" or "su" available to make this happen.
			EOF
    exit 1
  fi
fi

declare -A download_link
download_link=(["arm32"]="https://tiptime-api.com/cdn/tt_installer/tt_installer_arm" ["arm64"]="https://tiptime-api.com/cdn/tt_installer/tt_installer_arm64" ["amd64"]="https://down.liumou.site/tt/tt_installer_amd64")

if ! $sh_c "wget -q -O $TTMANAGER_EXE ${download_link[$ARCH]} > /dev/null && chmod +x $TTMANAGER_EXE"
then
    echo "下载失败，频率过高，请稍后尝试"
fi

$sh_c "chmod +x $TTMANAGER_EXE"
$sh_c "$TTMANAGER_EXE"
