#!/usr/bin/env bash
#
# alpha custom miner — translate HiveOS flight-sheet vars into miner.conf
#
# Wrapper revision 1.3.0.1 (alpha-miner 1.3.0 + wrapper rev 1) changes:
#   - Multiple / failover pools: the flight-sheet "Pool URL" (CUSTOM_URL) may
#     contain several endpoints separated by comma, whitespace or newline.
#     They are written as a POOLS[] array; h-run.sh fails over between them.
#   - Robust extra-arg passthrough: any alpha-miner flag placed in the
#     flight-sheet extra config (CUSTOM_USER_CONFIG) is forwarded verbatim,
#     one token per whitespace/newline (e.g. --devices 0,1,2 --force-backend
#     ampere --status-interval 20 --sync-proof-submit).
#   - Wrapper tunables: lines of the form FAILOVER_*=N / REPORT_METRIC=... /
#     HSTATS_RAW_LINES=N in the extra config are routed to wrapper config
#     instead of being passed to the miner.

# Detect script location
[[ -z $SCRIPT_PATH ]] && SCRIPT_PATH=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
[[ -z $MINER_DIR ]] && MINER_DIR=/hive/miners/custom

# Source manifest
[[ -f $SCRIPT_PATH/h-manifest.conf ]] && source "$SCRIPT_PATH/h-manifest.conf"

conf_file="${CUSTOM_CONFIG_FILENAME:-$MINER_DIR/$CUSTOM_NAME/miner.conf}"

# ---- Flight-sheet inputs ---------------------------------------------------
wallet="$CUSTOM_TEMPLATE"
pass="${CUSTOM_PASS:-x}"

# ---- Parse pool list (comma / whitespace / newline separated) --------------
declare -a POOLS=()
# normalise separators to newlines, strip blanks
while IFS= read -r p || [[ -n "$p" ]]; do
    p="${p//[$'\t\r ']/}"
    [[ -n "$p" ]] && POOLS+=("$p")
done < <(printf '%s' "$CUSTOM_URL" | tr ',[:space:]' '\n')

if [[ ${#POOLS[@]} -eq 0 ]]; then
    echo "ERROR: no pool URL configured (CUSTOM_URL empty)" >&2
    # miner-run SOURCES this file — `return` from the sourced script (don't
    # `exit`, which would abort miner-run); fall back to exit if run directly.
    return 1 2>/dev/null || exit 1
fi

# ---- Split extra config into miner args vs. wrapper tunables ----------------
declare -a EXTRA_ARGS=()
declare -a WRAPPER_CFG=()
if [[ -n "$CUSTOM_USER_CONFIG" ]]; then
    # shellcheck disable=SC2206
    for tok in $CUSTOM_USER_CONFIG; do
        if [[ "$tok" =~ ^(FAILOVER_[A-Z0-9_]+|REPORT_METRIC|HSTATS_RAW_LINES)=.+$ ]]; then
            WRAPPER_CFG+=("$tok")
        else
            EXTRA_ARGS+=("$tok")
        fi
    done
fi

# ---- Base miner args (NO --pool here; h-run.sh adds it per failover) --------
# --status-interval default keeps per-card status lines fresh for h-stats.sh;
# if the user passes their own --status-interval in extra config it appears
# later on the command line and wins (alpha-miner = last-arg-wins).
declare -a BASE_ARGS=( --address "$wallet" --status-interval 30 )
if [[ -n "$pass" && "$pass" != "x" ]]; then
    BASE_ARGS+=( --password "$pass" )
fi
BASE_ARGS+=( "${EXTRA_ARGS[@]}" )

# ---- Write miner.conf ------------------------------------------------------
{
    printf '# generated by h-config.sh v%s — do not edit by hand\n' "$CUSTOM_VERSION"
    printf 'POOLS=('
    for p in "${POOLS[@]}"; do printf ' %q' "$p"; done
    printf ' )\n'
    printf 'ALPHA_BASE_ARGS=('
    for a in "${BASE_ARGS[@]}"; do printf ' %q' "$a"; done
    printf ' )\n'
    # Wrapper tunables (optional; h-run.sh / h-stats.sh apply defaults if unset)
    for kv in "${WRAPPER_CFG[@]}"; do
        printf '%s\n' "$kv"
    done
    # Kept for humans / backward compatibility
    printf 'POOL_URL=%q\n' "${POOLS[0]}"
    printf 'WALLET=%q\n' "$wallet"
} > "$conf_file"

echo "Configuration written to $conf_file"
echo "Pools (${#POOLS[@]}): ${POOLS[*]}"
echo "Base args: ${BASE_ARGS[*]}"
if [[ ${#WRAPPER_CFG[@]} -gt 0 ]]; then echo "Wrapper cfg: ${WRAPPER_CFG[*]}"; fi

# HiveOS miner_config_gen does `. h-config.sh` (sources this); the framework
# treats the sourced return status as config success. The final command MUST
# exit 0 — never leave a short-circuited `&&`/`[[ ]]` as the last status, or
# `( config_miner ) || exit $?` aborts miner-run and the miner never starts.
return 0 2>/dev/null || exit 0
