#!/bin/sh
REAL=/usr/bin/cgminer.real
CONF=/config/cgminer.conf
LINK=/tmp/cgminer

# Symlink for correct process name (dashd checks --miner-executable-name=cgminer)
ln -sf "$REAL" "$LINK"

# Check if any SSL pools exist
if ! grep -q 'stratum+ssl://' "$CONF" 2>/dev/null; then
    exec $LINK "$@"
fi

# Create temp config with SSL URLs replaced by per-slot proxy
TMPCONF=/tmp/cgminer_ssl.conf
cp "$CONF" "$TMPCONF"

# Extract pool URLs in order to temp file (avoids pipe subshell)
TMPURLS=/tmp/pool_urls.txt
grep -o '"url" *: *"[^"]*"' "$CONF" > "$TMPURLS" 2>/dev/null

SLOT=0
while IFS= read -r LINE; do
    URL=$(echo "$LINE" | grep -o 'stratum[^"]*')
    case "$URL" in
        stratum+ssl://*)
            PORT=$((33300 + SLOT))
            sed -i "s|$URL|stratum+tcp://127.0.0.1:$PORT|" "$TMPCONF"
            ;;
    esac
    SLOT=$((SLOT + 1))
done < "$TMPURLS"
rm -f "$TMPURLS"

# Replace config path in dashd's arguments
ARGS=""
SKIP_NEXT=0
for arg in "$@"; do
    if [ "$SKIP_NEXT" = "1" ]; then
        ARGS="$ARGS $TMPCONF"
        SKIP_NEXT=0
    elif [ "$arg" = "--default-config" ]; then
        ARGS="$ARGS $arg"
        SKIP_NEXT=1
    else
        ARGS="$ARGS $arg"
    fi
done

exec $LINK $ARGS
