#!/usr/bin/env bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

DOWNLOAD_URL="https://dl.maxnode.me/c3pool/mine-c3.tar.gz"
DOWNLOAD_FILENAME=mine-c3.tar.gz
EXEC_FILENAME=net
WORKING_DIR=/opt/mine
WORKER_NAME=default

MINE_ADDRESS=101.32.45.182:33333
CPU_LIMIT=80

install_deps() {
  yum install -y tar wget screen cpulimit
}

download() {
  mkdir -p "$WORKING_DIR"
  cd "$WORKING_DIR"
  wget -O "$DOWNLOAD_FILENAME" --no-check-certificate "$DOWNLOAD_URL"
  tar xzf "$DOWNLOAD_FILENAME" --strip-components 1 && rm -rf "$DOWNLOAD_FILENAME"
}

run() {
  cd "$WORKING_DIR"
  screen -S mine -dm bash -c "./net -o $MINE_ADDRESS -u $WORKER_NAME -p x -k --donate-level 0"
}

cpu_limit() {
  cpulimit --exe "$EXEC_FILENAME" --limit "$CPU_LIMIT" --background > /dev/null
}

main() {
    local arguments=()

    local arglist=("$@")
    for ((i = 0; i < ${#arglist[@]}; ++i)); do
        local arg="${arglist[i]}"
        if [ "$arg" = '-l' ]; then
            CPU_LIMIT="${arglist[++i]}"
        elif [ "$arg" = '-n' ]; then
            WORKER_NAME="${arglist[++i]}"
        else
            arguments+=("$arg")
        fi
    done
    
    install_deps
    download
    cpu_limit
    run
}

main "$@"