#!/usr/bin/env bash

# Function to remove quotes
remove_quotes() {
  local str="$1"
  str="${str%\"}"
  str="${str#\"}"
  echo "$str"
}

# Sanitize Environment Variables
for var_name in OPTIONS CUSTOM_COMMAND ALGO1 ALGO2 ALGO3 ALGO4 WALLET_ADDRESS_ALGO1 WALLET_ADDRESS_ALGO2 WALLET_ADDRESS_ALGO3 WALLET_ADDRESS_ALGO4 POOL_ALGO1 POOL_ALGO2 POOL_ALGO3 POOL_ALGO4 WORKER_ALGO1 WORKER_ALGO2 WORKER_ALGO3 WORKER_ALGO4 PASSWORD_ALGO1 PASSWORD_ALGO2 PASSWORD_ALGO3 PASSWORD_ALGO4; do
  eval "value=\$$var_name"
  value=$(remove_quotes "$value")
  eval "$var_name=\"$value\""
done

# Fetch the latest release URL
LATEST_RELEASE_URL=$(curl -s https://api.github.com/repos/nanopool/nanominer/releases/latest | jq -r ".assets[] | select(.name | test(\"linux\")) | .browser_download_url")

# Download the tarball
wget $LATEST_RELEASE_URL -O /root/nanominer-linux.tar.gz

# Extract the tarball
tar --strip-components=0 -xzf /root/nanominer-linux.tar.gz -C /root


# Initialize an empty config string
config=""

# Construct the header based on the environment variables
header="; Crypto and Coffee autogenerated config file\n"
header+="checkForUpdates = $CHECK_FOR_UPDATES\n"
header+="mport = $MPORT\n"
header+="noLog = $NO_LOG\n"
header+="webPort = $WEB_PORT\n"
header+="noColor = $NO_COLOR\n\n"

# Function to generate config for an algorithm
generate_config() {
  local algo=$1
  local wallet_address=$2
  local pool=$3
  local worker=$4
  local password=$5

  local algo_config=""

  if [ ! -z "$wallet_address" ]; then
    algo_config+="[$algo]\nwallet = $wallet_address\n"
    [ ! -z "$pool" ] && algo_config+="pool1 = $pool\n"
    [ ! -z "$worker" ] && algo_config+="rigname = $worker\n"
    [ ! -z "$password" ] && algo_config+="rigPassword = $password\n"

    # If the algorithm contains "zil" (case-insensitive), add zilEpoch = 0
    if [[ "$algo" =~ [zZ][iI][lL] ]]; then
      algo_config+="zilEpoch = 0\n"
    fi
  fi

  echo -n "$algo_config"
}

# Generate and append config for each algorithm
[ ! -z "$ALGO1" ] && config+="$(generate_config "$ALGO1" "$WALLET_ADDRESS_ALGO1" "$POOL_ALGO1" "$WORKER_ALGO1" "$PASSWORD_ALGO1")\n"
[ ! -z "$ALGO2" ] && config+="$(generate_config "$ALGO2" "$WALLET_ADDRESS_ALGO2" "$POOL_ALGO2" "$WORKER_ALGO2" "$PASSWORD_ALGO2")\n"
[ ! -z "$ALGO3" ] && config+="$(generate_config "$ALGO3" "$WALLET_ADDRESS_ALGO3" "$POOL_ALGO3" "$WORKER_ALGO3" "$PASSWORD_ALGO3")\n"
[ ! -z "$ALGO4" ] && config+="$(generate_config "$ALGO4" "$WALLET_ADDRESS_ALGO4" "$POOL_ALGO4" "$WORKER_ALGO4" "$PASSWORD_ALGO4")\n"

# Remove the trailing newline from the config string
config=${config%$'\n'}

# Write the config to a file, but only if config is not empty
if [ ! -z "$config" ]; then
  echo -e "$header$config" > config.ini
fi

if [[ -n "$CUSTOM_COMMAND" ]]; then
  echo "Using custom command: $CUSTOM_COMMAND"
  /root/nanominer $CUSTOM_COMMAND
else
  echo "Using configuration from config.ini:"
  cat config.ini
  /root/nanominer
fi
