#!/bin/bash
# BitBull Monitor — one-command installer
# Usage: curl -fsSL https://monitor.bitbulltech.com/install.sh | sudo bash
set -euo pipefail

BASE_URL="${BITBULL_INSTALL_URL:-https://monitor.bitbulltech.com}"
VERSION="${BITBULL_VERSION:-}"
INSTALL_DIR="${INSTALL_DIR:-/opt/bitbull-monitor}"
DATA_DIR="${DATA_DIR:-/var/lib/bitbull-monitor}"
PORT="${PORT:-1987}"
SERVICE_NAME="bitbull-monitor"
ENV_FILE="/etc/bitbull-monitor.env"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

info()  { echo -e "${GREEN}==>${NC} $*"; }
warn()  { echo -e "${YELLOW}==>${NC} $*"; }
error() { echo -e "${RED}ERROR:${NC} $*" >&2; exit 1; }

if [ "$(id -u)" -ne 0 ]; then
  error "Please run as root: curl -fsSL $BASE_URL/install.sh | sudo bash"
fi

for cmd in curl tar sha256sum systemctl; do
  command -v "$cmd" >/dev/null 2>&1 || error "Required command not found: $cmd"
done

ARCH="$(uname -m)"
case "$ARCH" in
  x86_64)         GOARCH=amd64 ;;
  aarch64|arm64)  GOARCH=arm64 ;;
  *) error "Unsupported architecture: $ARCH (need x86_64 or aarch64)" ;;
esac

if [ -z "$VERSION" ]; then
  info "Fetching latest version from $BASE_URL/releases/latest.txt"
  VERSION="$(curl -fsSL "$BASE_URL/releases/latest.txt" | tr -d '[:space:]')"
fi

[ -n "$VERSION" ] || error "Could not determine release version"

RELEASE_URL="$BASE_URL/releases/$VERSION"
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT

PKG="bitbull-monitor-linux-${GOARCH}.tar.gz"
info "Installing BitBull Monitor ${VERSION} (${GOARCH})"

curl -fsSL "$RELEASE_URL/$PKG" -o "$TMP/$PKG"
curl -fsSL "$RELEASE_URL/SHA256SUMS" -o "$TMP/SHA256SUMS"

(
  cd "$TMP"
  grep -F "$PKG" SHA256SUMS | sha256sum -c -
)

mkdir -p "$INSTALL_DIR" "$DATA_DIR"
tar -xzf "$TMP/$PKG" -C "$INSTALL_DIR"
chmod +x "$INSTALL_DIR/bitbull-monitor"

if [ ! -f "$ENV_FILE" ]; then
  if command -v openssl >/dev/null 2>&1; then
    JWT_SECRET="$(openssl rand -hex 32)"
  else
    JWT_SECRET="$(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')"
  fi
  cat > "$ENV_FILE" <<EOF
# BitBull Monitor environment — created by install.sh
DATA_DIR=$DATA_DIR
PORT=$PORT
HOST=0.0.0.0
JWT_SECRET=$JWT_SECRET
EOF
  chmod 600 "$ENV_FILE"
  info "Created $ENV_FILE"
else
  warn "Keeping existing $ENV_FILE"
fi

cp "$INSTALL_DIR/bitbull-monitor.service" "/etc/systemd/system/${SERVICE_NAME}.service"
systemctl daemon-reload
systemctl enable "$SERVICE_NAME"
systemctl restart "$SERVICE_NAME"

sleep 2
if ! systemctl is-active --quiet "$SERVICE_NAME"; then
  warn "Service may have failed to start. Check: journalctl -u $SERVICE_NAME -n 50"
else
  info "Service started successfully"
fi

IP="$(hostname -I 2>/dev/null | awk '{print $1}')"
IP="${IP:-YOUR_SERVER_IP}"

echo ""
echo "============================================"
echo "  BitBull Monitor installed successfully!"
echo "============================================"
echo ""
echo "  Version:  $VERSION"
echo "  URL:      http://${IP}:${PORT}"
echo "  Login:    admin / admin"
echo "            (password change required on first login)"
echo ""
echo "  Service:  systemctl status $SERVICE_NAME"
echo "  Logs:     journalctl -u $SERVICE_NAME -f"
echo "  Data:     $DATA_DIR"
echo "  Config:   $ENV_FILE"
echo ""
echo "  Firewall: ensure port ${PORT} is open if accessing remotely"
echo "============================================"
