#!/usr/bin/env bash
# Builds command-line arguments for hasher from Hive OS Flight Sheet fields.
# Pool URL              -> --pool <CUSTOM_URL>
# Wallet/work template  -> --wallet <CUSTOM_TEMPLATE>
# Extra config args     -> appended as-is, e.g. --nvidia-ocl

set -euo pipefail

miner_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
[[ -f "$miner_dir/h-manifest.conf" ]] && . "$miner_dir/h-manifest.conf"

mkdir -p "$(dirname "$CUSTOM_CONFIG_FILENAME")"
mkdir -p "$(dirname "$CUSTOM_LOG_BASENAME")"

trim() {
  local s="${1:-}"
  s="${s#"${s%%[![:space:]]*}"}"
  s="${s%"${s##*[![:space:]]}"}"
  printf '%s' "$s"
}

pool="$(trim "${CUSTOM_URL:-}")"
wallet="$(trim "${CUSTOM_TEMPLATE:-}")"
extra="$(trim "${CUSTOM_USER_CONFIG:-}")"

cmd=""

if [[ -n "$pool" ]]; then
  cmd+=" --pool $(printf '%q' "$pool")"
fi

if [[ -n "$wallet" ]]; then
  cmd+=" --wallet $(printf '%q' "$wallet")"
fi

if [[ -n "$extra" ]]; then
  # Extra config is intentionally appended raw, so Hive users can pass any miner-specific flags.
  cmd+=" $extra"
fi

printf '%s\n' "${cmd# }" > "$CUSTOM_CONFIG_FILENAME"
