#!/usr/bin/env bash
set -euo pipefail

STRATUM_DIR="${STRATUM_DIR:-/opt/vexon-pool/stratum}"
STRATUM_CONFIG_DIR="${STRATUM_CONFIG_DIR:-/opt/vexon-pool/stratum-config}"
STRATUM_CONFIG_NAME="${STRATUM_CONFIG_NAME:-vexon}"
SCREEN_NAME="${SCREEN_NAME:-Vexon_Stratum}"

repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
timestamp="$(date +%F-%H%M%S)"

mkdir -p "$STRATUM_DIR" "$STRATUM_CONFIG_DIR"

cd "$repo_dir"
make clean
make

if [[ ! -x "$repo_dir/stratum" ]]; then
  echo "Build did not produce executable: $repo_dir/stratum" >&2
  exit 1
fi

screen -S "$SCREEN_NAME" -X quit >/dev/null 2>&1 || true
sleep 2

for target in "$STRATUM_DIR/VexonStratum" "$STRATUM_CONFIG_DIR/VexonStratum"; do
  if [[ -e "$target" ]]; then
    cp -av "$target" "$target.bak.$timestamp"
  fi
  cp -av "$repo_dir/stratum" "$target"
  chmod +x "$target"
done

cd "$STRATUM_CONFIG_DIR"
screen -dmS "$SCREEN_NAME" ./run.sh "$STRATUM_CONFIG_NAME"

echo "Installed VexonStratum and restarted $SCREEN_NAME with config $STRATUM_CONFIG_NAME"
ps -ef | grep -E 'VexonStratum|vexon' | grep -v grep || true
