#!/bin/bash

LOGFILE="/var/log/miner_script.log"
WORK_DIR=$(pwd)

CPU_CORES=$(lscpu | awk '/^CPU\(s\):/{print $2}')

if pgrep -x "monitor.sh" >/dev/null; then
    echo "$(date +"%Y-%m-%d %H:%M:%S")     INFO Another instance of monitor.sh is already running. Exiting..."
else
    source /etc/profile
    nohup $WORK_DIR/monitor.sh >> $WORK_DIR/.monitor.sh 2>&1 &
fi

[ -t 1 ] && . colors

ACCOUNTNAME=$(grep 'CUSTOM_PASS' /hive-config/wallet.conf | awk -F '=' '{print $2}' | tr -d '"')

CUSTOM_TEMPLATE=$(grep 'CUSTOM_TEMPLATE' /hive-config/wallet.conf | awk -F '=' '{print $2}' | tr -d '"')
echo "Sub-accounts are: $CUSTOM_TEMPLATE" >> $LOGFILE

update_wallet_conf() {
    sed -i 's/"coin":"QUBIC"/"coin":"ALEO"/' /hive-config/wallet.conf
}

revert_wallet_conf() {
    sed -i 's/"coin":"ALEO"/"coin":"QUBIC"/' /hive-config/wallet.conf
}

source apoolminer_hiveos_qubic_aleo_idle_f2_mining.conf
echo $PROXY >> $LOGFILE
source h-manifest.conf
echo $MINER_REST_PORT >> $LOGFILE
source "$CUSTOM_CONFIG_FILENAME"

HOSTNAME=$(hostname)
[[ -z $CUSTOM_LOG_BASENAME ]] && { echo -e "${RED}No CUSTOM_LOG_BASENAME is set${NOCOLOR}"; exit 1; }
[[ -z $CUSTOM_CONFIG_FILENAME ]] && { echo -e "${RED}No CUSTOM_CONFIG_FILENAME is set${NOCOLOR}"; exit 1; }
[[ ! -f $CUSTOM_CONFIG_FILENAME ]] && { echo -e "${RED}Custom config ${YELLOW}$CUSTOM_CONFIG_FILENAME${RED} is not found${NOCOLOR}"; exit 1; }

CUSTOM_LOG_BASEDIR=$(dirname "${CUSTOM_LOG_BASENAME}")
[[ ! -d $CUSTOM_LOG_BASEDIR ]] && mkdir -p "$CUSTOM_LOG_BASEDIR"

while true; do
    response=$(curl -s http://qubic1.hk.apool.io:8001/api/qubic/epoch_challenge | grep -o '"mining_seed":"[^"]*"' | sed 's/.*"mining_seed":"\([^"]*\)".*/\1/')
    echo "$(date) - Detected Response: $response" >> $LOGFILE

    if [ "$response" == "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" ]; then
        echo "$(date) - Correct response. Update wallet.conf to ALEO." >> $LOGFILE
        update_wallet_conf
        echo "$(date) - Restart the miner..." >> $LOGFILE

        echo "$(date) - Start ALEO miner" >> $LOGFILE
        if [ "$CPU_CORES" -eq 2 ]; then
            taskset -c 1 ./aleominer  $ACCOUNTNAME.$(hostname) | tee --append "${CUSTOM_LOG_BASENAME}.log"
        else
            ./aleominer  $ACCOUNTNAME.$(hostname) | tee --append "${CUSTOM_LOG_BASENAME}.log"
        fi
    else
        echo "$(date) - Keep or restore to QUBIC." >> $LOGFILE
        revert_wallet_conf

        if ! pgrep -f 'apoolminer.*account'; then
            echo "Running $NVTOOL" | tee -a ${CUSTOM_LOG_BASENAME}.log
            echo "$(date) - Launch QUBIC Miner" >> $LOGFILE
            if [ "$CPU_CORES" -eq 2 ]; then
                taskset -c 0 ./apoolminer --account "$CUSTOM_TEMPLATE" --pool $PROXY --rest --port "$MINER_REST_PORT" -A qubic $EXTRA 2>&1 | tee --append "${CUSTOM_LOG_BASENAME}.log"
            else
                ./apoolminer --account "$CUSTOM_TEMPLATE" --pool $PROXY --rest --port "$MINER_REST_PORT" -A qubic $EXTRA 2>&1 | tee --append "${CUSTOM_LOG_BASENAME}.log"
            fi
        fi
    fi

    echo "$(date) - The cycle ends and waits for the next detection..." >> $LOGFILE
done
