#!/bin/bash

set -e

if [[ $EUID -ne 0 ]]; then
  echo "This script must be run as root"
  exit 1
fi

URL="https://waf-ce.chaitin.cn/release/latest/manager.py"
FILE_NAME="/tmp/safeline.py"

check_python3_installed() {
  if command -v python3 &>/dev/null; then
    return 0
  else
    return 1
  fi
}

detect_os() {
  if [ -f /etc/os-release ]; then
    . /etc/os-release
    echo $ID
  else
    echo "unknown"
  fi
}

install_python_ubuntu_debian() {
  apt update
  apt install -y python3 python3-pip
}

install_python_centos() {
  yum update
  yum install -y python3
}

install_python_alpine() {
  apk update
  apk add python3 py3-pip
}

# 主安装逻辑
if ! check_python3_installed; then
  OS=$(detect_os)
  case $OS in
    ubuntu|debian)
      install_python_ubuntu_debian
      ;;
    centos|rhel)
      install_python_centos
      ;;
    alpine)
      install_python_alpine
      ;;
    *)
      echo "failed to detect OS: $OS"
      echo "please install Python 3 manually and run this script again."
      exit 1
      ;;
  esac
fi

curl -4sSLk -o "$FILE_NAME" "$URL"

python3 "$FILE_NAME" "$@"
