#!/usr/bin/env bash
. h-manifest.conf

cd /hive/miners/custom/$CUSTOM_NAME || exit 1

# Best-effort template retrieval (HiveOS varies by setup)
tpl=""
if [[ -n "$CUSTOM_TEMPLATE" ]]; then
  tpl="$CUSTOM_TEMPLATE"
elif [[ -n "$TEMPLATE" ]]; then
  tpl="$TEMPLATE"
elif [[ -n "$WALLET" ]]; then
  tpl="$WALLET"
elif [[ -n "$WAL" ]]; then
  tpl="$WAL"
fi

# Fallback: parse existing miner.conf from prior run
if [[ -z "$tpl" && -f "$CUSTOM_CONFIG_FILENAME" ]]; then
  prev_miner=$(grep -oE '(-miner[[:space:]]+[^[:space:]]+)' "$CUSTOM_CONFIG_FILENAME" | awk '{print $2}' | tail -n1)
  prev_worker=$(grep -oE '(-worker[[:space:]]+[^[:space:]]+)' "$CUSTOM_CONFIG_FILENAME" | awk '{print $2}' | tail -n1)
  if [[ -n "$prev_miner" || -n "$prev_worker" ]]; then
    MINER_NAME="$prev_miner"
    WORKER_NAME="$prev_worker"
  fi
fi

# Derive names from tpl if not already set
if [[ -z "$MINER_NAME" || -z "$WORKER_NAME" ]]; then
  if [[ -n "$tpl" && "$tpl" == *.* ]]; then
    MINER_NAME="${tpl%%.*}"
    WORKER_NAME="${tpl##*.}"
  elif [[ -n "$tpl" ]]; then
    MINER_NAME="$tpl"
    WORKER_NAME="${HIVE_WORKER_NAME:-default}"
  else
    MINER_NAME="${HIVE_WORKER_NAME:-mcminer}"
    WORKER_NAME="${HIVE_WORKER_NAME:-default}"
  fi
fi

# Replace placeholder with actual worker name if present
if [[ "$WORKER_NAME" == *"%WORKER_NAME%"* ]]; then
  WORKER_NAME="${HIVE_WORKER_NAME:-$WORKER_NAME}"
fi

# Pretty banner
bar='━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'
echo "Moonclub AMADEUS MINER DASHBOARD"
date_line=$(date +"%Y-%m-%d %H:%M:%S %Z")
echo "Moonclub $date_line"
echo "Moonclub $bar"
echo "Moonclub "
echo "Moonclub ----- MINER INFO -------------------------------------------"
echo "Moonclub Name: $MINER_NAME"
echo "Moonclub Worker: $WORKER_NAME"
echo "Moonclub Pool: moonclub"
echo "Moonclub $bar"

# DEBUG block (kept to verify environment on rigs)
echo "Moonclub DEBUG CUSTOM_TEMPLATE=${CUSTOM_TEMPLATE}"
echo "Moonclub DEBUG TEMPLATE=${TEMPLATE}"
echo "Moonclub DEBUG WALLET=${WALLET}"
echo "Moonclub DEBUG HIVE_WORKER_NAME=${HIVE_WORKER_NAME}"

# Launch with supported flags only
./mcminer-go       -miner "$MINER_NAME"       -worker "$WORKER_NAME"       -optimize-for "cuda"       -pool-name "moonclub"       -log-path "$CUSTOM_LOG_BASENAME.log" 2>&1 | while read -r line; do
    ((count++))
    if [ $count -gt 10 ]; then
      echo "Moonclub $line"
    else
      echo "$line"
    fi
  done | tee --append $CUSTOM_LOG_BASENAME.log
