#!/usr/bin/env bash
#
# Paritr Node - management helper
#
#   ./manage.sh status              Show service status
#   ./manage.sh logs                Live logs
#   ./manage.sh restart             Restart the service
#   ./manage.sh address P...        Set the mining wallet
#   ./manage.sh secret              Show the admin secret key
#   ./manage.sh mining on|off       Turn mining on or off
#   ./manage.sh cores <n>           Mining worker processes (0 = automatic)
#   ./manage.sh intensity <5-100>   Load per worker process in percent
#   ./manage.sh cpuquota <n%>       Hard CPU limit via systemd (200% = 2 cores)
#   ./manage.sh publicurl [url]     Show, detect or set the public address
#   ./manage.sh peers               Show known peers
#   ./manage.sh addpeer <url>       Add a peer manually
#   ./manage.sh rmpeer <url>        Remove a peer (e.g. dead CDN addresses)
#   ./manage.sh update <base-url>   Update node.py from the web portal
#
set -euo pipefail

SERVICE_NAME="paritr-node"
NODE_DIR="${PARITR_DIR:-$HOME/paritr-node}"
CONFIG="$NODE_DIR/config.json"

read_config() { python3 -c "import json,sys;print(json.load(open('$CONFIG')).get('$1',''))"; }
rpc_port() { read_config rpc_port; }
secret() { read_config admin_secret; }

admin_post() {
  curl -fsS -X POST "http://127.0.0.1:$(rpc_port)$1" \
    -H "Content-Type: application/json" -H "X-Admin-Secret: $(secret)" \
    -d "$2" | python3 -m json.tool
}

case "${1:-status}" in
  status)
    sudo systemctl --no-pager status "$SERVICE_NAME" || true
    curl -fsS "http://127.0.0.1:$(rpc_port)/status" | python3 -m json.tool || true
    ;;
  logs)
    journalctl -u "$SERVICE_NAME" -f
    ;;
  start|stop|restart)
    sudo systemctl "$1" "$SERVICE_NAME"
    ;;
  address)
    [[ $# -ge 2 ]] || { echo "Usage: $0 address <wallet address>"; exit 1; }
    admin_post /admin/mining "{\"miner_address\": \"$2\"}"
    ;;
  mining)
    [[ $# -ge 2 ]] || { echo "Usage: $0 mining on|off"; exit 1; }
    STATE=$([[ "$2" == "on" ]] && echo true || echo false)
    admin_post /admin/mining "{\"mining_enabled\": $STATE}"
    ;;
  cores)
    [[ $# -ge 2 ]] || { echo "Usage: $0 cores <count|0 for automatic>"; exit 1; }
    admin_post /admin/mining "{\"mining_processes\": $2}"
    ;;
  intensity)
    [[ $# -ge 2 ]] || { echo "Usage: $0 intensity <5-100>"; exit 1; }
    admin_post /admin/mining "{\"mining_intensity\": $2}"
    ;;
  cpuquota)
    [[ $# -ge 2 ]] || { echo "Usage: $0 cpuquota <n%>  (200% = 2 cores)"; exit 1; }
    sudo systemctl set-property "$SERVICE_NAME" "CPUQuota=$2"
    echo "CPU limit set to $2."
    ;;
  publicurl)
    # Without an argument the address is detected and only suggested; the
    # config is rewritten solely when a value is passed explicitly.
    if [[ $# -ge 2 ]]; then
      python3 - "$CONFIG" "$2" <<'PY'
import json, sys
path, url = sys.argv[1], sys.argv[2]
with open(path) as handle:
    config = json.load(handle)
config["public_url"] = url
with open(path, "w") as handle:
    json.dump(config, handle, indent=2)
print("public_url set to", url or "<none>")
PY
      sudo systemctl restart "$SERVICE_NAME"
    else
      echo "Configured: $(read_config public_url)"
      echo "Detected  : $("$NODE_DIR/venv/bin/python" "$NODE_DIR/node.py" --detect-public-url || true)"
    fi
    ;;
  secret)
    secret
    ;;
  peers)
    curl -fsS "http://127.0.0.1:$(rpc_port)/admin/peers" \
      -H "X-Admin-Secret: $(secret)" | python3 -m json.tool
    ;;
  addpeer)
    [[ $# -ge 2 ]] || { echo "Usage: $0 addpeer <url>"; exit 1; }
    admin_post /admin/peers/add "{\"url\": \"$2\"}"
    ;;
  rmpeer)
    [[ $# -ge 2 ]] || { echo "Usage: $0 rmpeer <url>"; exit 1; }
    admin_post /admin/peers/remove "{\"url\": \"$2\"}"
    ;;
  update)
    [[ $# -ge 2 ]] || { echo "Usage: $0 update <base-url>"; exit 1; }
    curl -fsSL "$2/node.py" -o "$NODE_DIR/node.py.new"
    curl -fsSL "$2/wsgi.py" -o "$NODE_DIR/wsgi.py.new"
    mv "$NODE_DIR/node.py.new" "$NODE_DIR/node.py"
    mv "$NODE_DIR/wsgi.py.new" "$NODE_DIR/wsgi.py"
    sudo systemctl restart "$SERVICE_NAME"
    echo "Node updated and restarted."
    ;;
  *)
    grep '^#' "$0" | sed 's/^# \{0,1\}//'
    ;;
esac
