#!/usr/bin/env bash
# OneZeroMiner 1.8.5 EXPERIMENTAL / PearlHash only. Does not prove elimination of dev fees.
# Usage: sudo bash install-ozm184-patch.sh [absolute-miner-path] [api-port]
set -Eeuo pipefail
umask 077

URL='https://www.12345.la/prl/ozm184-native-patch-1.1.0-linux-x86_64.gz'
PACKAGE_SHA='e7b741437149cfc4125b2cf3e75b3f22dc47c4504afd518b8da6aa4a36b8c08e'
MINER_SHA='326bf09142b5b4b6a3a603da32d37998283425ba67d937a201e4588ea55d8b33'
UNIT='ozm185-native-patch.service'
PATCH='/opt/ozm185-native-patch/ozm185-patch'
MINER=${1:-/root/onezerominer/onezerominer}
PORT=${2:-3001}
STARTED=0
WORK=''

die() { echo "ERROR: $*" >&2; exit 1; }
cleanup() {
    local rc=$?
    trap - EXIT
    if (( rc != 0 && STARTED == 1 )); then
        echo 'Verification failed; stopping and disabling the new patch service.' >&2
        systemctl disable "$UNIT" || true
        systemctl stop "$UNIT" || true
        journalctl -u "$UNIT" -n 15 --no-pager || true
        echo 'Inspect service logs for restore confirmation before retrying.' >&2
    fi
    if [[ -n "$WORK" ]]; then echo "Installer files retained: $WORK"; fi
    exit "$rc"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM

[[ $EUID -eq 0 ]] || die 'Run with sudo bash (HiveOS root shell needs no sudo).'
[[ $(uname -s) == Linux && $(uname -m) == x86_64 ]] || die 'Linux x86_64 required.'
[[ $# -le 2 ]] || die 'Usage: script [absolute-miner-path] [api-port]'
[[ $PORT =~ ^[0-9]{1,5}$ ]] || die 'Invalid API port.'
PORT=$((10#$PORT))
(( PORT >= 1 && PORT <= 65535 )) || die 'Invalid API port.'
[[ $MINER == /* && -f $MINER ]] || die "Miner file not found: $MINER"
for cmd in curl sha256sum tar gcc systemctl jq readlink flock; do
    command -v "$cmd" >/dev/null || die "Missing command: $cmd (nothing installed)."
done
[[ -d /run/systemd/system ]] || die 'Running systemd required.'
exec 9>/run/ozm-miner-patch-installer.lock
flock -n 9 || die 'Another installer is running.'
MINER=$(readlink -f "$MINER")
ACTUAL=$(sha256sum "$MINER")
[[ ${ACTUAL%% *} == "$MINER_SHA" ]] || die 'Unsupported miner SHA256; do not force installation.'

# Refuse to overwrite any previous installation or silently restart a safety-blocked process.
if [[ -e /etc/systemd/system/ozm184-native-patch.service || -e /etc/systemd/system/$UNIT || -e $PATCH || -e /opt/ozm184-fee-patch/ozm184_patch.py ]]; then
    echo 'Existing patch installation found. No changes made.'
    echo "Inspect with: sudo $PATCH status"
    echo 'For 1.8.4 uninstall: sudo /opt/ozm184-native-patch/ozm184-patch uninstall'
    echo 'Do not run two patch services together.'
    exit 2
fi

WORK=$(mktemp -d /root/ozm185-install.XXXXXX)
cd "$WORK"
echo '[1/5] Downloading pinned package...'
curl -fL --proto '=https' --proto-redir '=https' --retry 3 \
    --connect-timeout 15 --max-time 240 "$URL" -o package.gz
printf '%s  package.gz\n' "$PACKAGE_SHA" | sha256sum -c -
tar -xzf package.gz
cd ozm184-native-patch

sed -e 's/ozm184/ozm185/g' -e 's/1\.8\.4/1.8.5/g' \
    -e 's/#define VERSION "1.1.0"/#define VERSION "1.2.0-test1"/' \
    -e 's/7c2d68d61545cb121483fef76b6a1c2ab8fbeadab8e3ce737f76e19fd229b7ec/326bf09142b5b4b6a3a603da32d37998283425ba67d937a201e4588ea55d8b33/g' \
    -e 's/a.hash<1e15\&\&base.hash>1e15\&\&a.hash<base.hash\*.9/base.hash>0\&\&a.hash<base.hash*.9/' \
    ozm184-patch.c > ozm185-patch.c
printf '%s  ozm185-patch.c\n' '2bacee4f344788d7881f0e9dffa07c64aff684fc0fd414264f1f64d9231ec7b1' | sha256sum -c -
echo '[2/5] Building experimental 1.8.5 source...'
gcc -std=c11 -O2 -static -fstack-protector-strong -D_FORTIFY_SOURCE=2 \
    -Wall -Wextra -Werror -o ozm185-patch-reviewed ozm185-patch.c
./ozm185-patch-reviewed self-test
echo '[3/5] Checking running miner (read-only)...'
./ozm185-patch-reviewed check --miner "$MINER" --api-port "$PORT"
curl -fsS --max-time 5 "http://127.0.0.1:$PORT/" > "$WORK/before.json"

echo '[4/5] Installing service without restarting miner...'
STARTED=1
./ozm185-patch-reviewed install --miner "$MINER" --api-port "$PORT"

echo '[5/5] Waiting for verified memory readback (up to 30 seconds)...'
VERIFIED=0
for ((i=0; i<15; i++)); do
    sleep 2
    if systemctl is-active --quiet "$UNIT" &&
       jq -e --argjson now "$(date +%s)" \
         '.api_ok == true and ($now - .checked_epoch < 30) and
          any(.targets[]; .owned == true and .readback_matches == true and .blocked == false)' \
         /var/lib/ozm185-native-patch/status.json >/dev/null 2>&1; then
        VERIFIED=1
        break
    fi
done
(( VERIFIED == 1 )) || die 'No verified owned target.'
"$PATCH" status | tee "$WORK/verified-status.txt"
grep -q 'LIVE .*readback_matches=true' "$WORK/verified-status.txt" || die 'Live readback failed.'
STARTED=0
echo 'SUCCESS (experimental): patch applied and service enabled. Miner was not restarted.'
echo 'This proves memory patching only, NOT permanent zero dev fee or long-term stability.'
echo 'Watch accepted/rejected shares and hashrate. This experimental adaptation has not proven fee elimination.'
echo "Status:    sudo $PATCH status"
echo "Uninstall: sudo $PATCH uninstall"
