#!/bin/bash
# PrintMetrix Feeder — one-shot installer for Linux and macOS.
#
# Usage (must be run as root):
#   curl -fsSL https://printmetrix.com/download/install.sh | sudo bash
#
# The legacy URL https://printmetrix.com/install.sh still works
# (301 redirects to /download/install.sh) so older docs / scripts
# keep functioning. New deployments should reference /download/.
#
# Flow:
#   1. Detect OS + arch, pick the right binary
#   2. Download into /usr/local/bin/printmetrix-feeder
#   3. Prompt the user for a wizard-generated FEEDER-XXXX-XXXX claim code
#   4. Run `feeder claim --code` to save credentials
#   5. Run `feeder install` to drop the systemd unit / LaunchDaemon plist
#      and start the service
set -euo pipefail

BASE_URL="${PRINTMETRIX_BASE_URL:-https://printmetrix.com}"
INSTALL_DIR="/usr/local/bin"
SERVICE_NAME="printmetrix-feeder"
BINARY_PATH="$INSTALL_DIR/$SERVICE_NAME"

echo
echo "  PrintMetrix Feeder Installer"
echo "  ============================"
echo

# Must be root: writes to /usr/local/bin and creates a system service.
if [ "$(id -u)" != "0" ]; then
    echo "  Error: install.sh must run as root."
    echo "  Re-run with:"
    echo "    curl -fsSL $BASE_URL/install.sh | sudo bash"
    exit 1
fi

# Detect OS + arch.
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
RAW_ARCH="$(uname -m)"
case "$RAW_ARCH" in
    x86_64|amd64)         ARCH="amd64" ;;
    aarch64|arm64)        ARCH="arm64" ;;
    *)
        echo "  Unsupported architecture: $RAW_ARCH"
        echo "  Supported: x86_64, aarch64/arm64"
        exit 1
        ;;
esac
case "$OS" in
    linux)  BINARY="printmetrix-feeder-linux-$ARCH" ;;
    darwin) BINARY="printmetrix-feeder-darwin-$ARCH" ;;
    *)
        echo "  Unsupported OS: $OS"
        echo "  Supported: linux, darwin (macOS)"
        exit 1
        ;;
esac

echo "  Detected: $OS/$ARCH"
echo

# 1. Download ---------------------------------------------------------------
echo "  Downloading $BINARY..."
if ! curl -fsSL --connect-timeout 10 "$BASE_URL/downloads/$BINARY" -o "$BINARY_PATH"; then
    echo "  Download failed — check $BASE_URL/downloads/$BINARY"
    exit 1
fi
chmod +x "$BINARY_PATH"
echo "  Downloaded ✓"

# 2. Claim ------------------------------------------------------------------
echo
echo "  ==========================================================="
echo "  Connect to PrintMetrix:"
echo "    1. Open $BASE_URL in your browser"
echo "    2. Sign in and go to Feeders -> Setup"
echo "    3. Click 'Generate claim code'"
echo "  ==========================================================="
echo

# Read directly from the controlling terminal so this still works when
# the script itself is being piped from curl: `curl ... | sudo bash`.
if [ -t 0 ]; then
    PROMPT_FD=0
else
    exec 3</dev/tty || {
        echo "  Error: no controlling tty available for the claim-code prompt."
        echo "  Re-run interactively: sudo bash <(curl -fsSL $BASE_URL/install.sh)"
        exit 1
    }
    PROMPT_FD=3
fi

read -r -p "  Enter claim code (FEEDER-XXXX-XXXX): " CLAIM_CODE <&$PROMPT_FD
CLAIM_CODE="$(echo "$CLAIM_CODE" | tr '[:lower:]' '[:upper:]' | xargs)"
if [ -z "$CLAIM_CODE" ]; then
    echo "  No claim code entered — aborting."
    exit 1
fi

echo
echo "  Connecting to PrintMetrix..."
if ! "$BINARY_PATH" claim --code "$CLAIM_CODE"; then
    echo "  Claim failed — verify the code at $BASE_URL and retry."
    exit 1
fi

# 3. Service install --------------------------------------------------------
# `feeder install` copies the binary to the canonical service path,
# writes the systemd unit (Linux) or LaunchDaemon plist (macOS), and
# starts the service. The service reads the config file written by the
# claim step above.
echo "  Installing system service..."
if ! "$BINARY_PATH" install; then
    echo "  Service install failed."
    exit 1
fi

echo
echo "  ✅ PrintMetrix Feeder is installed and running!"
echo "     - Starts automatically on boot."
case "$OS" in
    linux)
        echo "     - Status: systemctl status $SERVICE_NAME"
        echo "     - Logs:   journalctl -u $SERVICE_NAME -f"
        ;;
    darwin)
        echo "     - Status: launchctl list com.printmetrix.feeder"
        echo "     - Logs:   /var/log/printmetrix-feeder.log"
        ;;
esac
echo
