#!/bin/sh
# Fail fast
set -e

# Check if telemetry is disabled
if [ "$TELEMETRY" != "off" ]; then
    # Cronitor uses Cronitor to monitor installations of CronitorCLI
    curl -s "https://cronitor.link/mBXClL?state=run&series=1749700212.009"
fi

# Detect the OS
os_out=`uname -s`
case $os_out in
Darwin*) os="darwin" ;;
Linux*) os="linux" ;;
FreeBSD*) os="freebsd" ;;
*) echo "unsupported OS $os_out, please let us know by sending us an email at support@cronitor.io" && exit 1 ;;
esac

# Detect the architecture
arch_out=`uname -m`
case $arch_out in
amd64*) architecture="amd64" ;;
x86_64*) architecture="amd64" ;;
arm64*) architecture="arm64" ;;
aarch64*) architecture="arm64" ;;
arm*) architecture="arm" ;;
*) echo "unsupported architecture $arch_out, please let us know by sending us an email at support@cronitor.io" && exit 1 ;;
esac

platform=$os\_$architecture
download=https://cronitor.io/dl/$platform.tar.gz

echo "Installing binary from $download"

# Fetch the current binary
curl -sOL $download

# Install location depends on OS
case $os_out in
Darwin*) dest=/usr/local/bin/ ;;
FreeBSD*) dest=/usr/local/bin/ ;;
Linux*) dest=/usr/bin/ ;;
*) echo "unsupported OS $os_out, please let us know by sending us an email at support@cronitor.io" && exit 1 ;;
esac
sudo tar xvf $platform.tar.gz -C $dest

# Test the installation and send an anonymous health ping to Cronitor
if [ "$TELEMETRY" != "off" ]; then
    cronitor && curl -s "https://cronitor.link/mBXClL?state=complete&series=1749700212.009" || curl -s "https://cronitor.link/mBXClL?state=fail&series=1749700212.009"
else
    cronitor
fi
echo "Installation successful. Starting the dashboard..."

cronitor dash --port 9000

