#!/usr/bin/env bash

ORANGE='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

check_installed() {
  if [ -f "$OAKCTL_BIN_PATH" ]; then
    echo -e "${BLUE}INFO${NC}: Already installed. Using self-update"
    "$OAKCTL_BIN_PATH" self-update
    check_path
    exit 0
  fi
}

get_system() {
  ARCH=$(uname -m)
  if [[ "$OSTYPE" == "linux-gnu" ]]; then
    if [[ "$ARCH" == 'x86_64' ]]; then
      SYSTEM="linux_x86_64"
    elif [[ "$ARCH" == 'aarch64' ]]; then
      SYSTEM="linux_aarch64"
    fi
  fi
  if [[ "$OSTYPE" == "darwin"* ]]; then
      SYSTEM="darwin_arm64"
  fi
  if [[ -f "/run/current-system/sw/bin/nixos-version" ]]; then
    echo "Use 'nix-shell -p oakctl' or add it to NixOS configuration"
    exit 0
  fi
  if [ -z "$SYSTEM" ]; then
    echo "Unsupported system"
    exit 1
  fi
}

download_version() {
  VERSION=$(curl -s "${OAKCTL_ADDRESS}/version")
}

download_oakctl() {
  mkdir -p "${OAKCTL_PATH}"
  EXECUTABLE_URL="${OAKCTL_ADDRESS}/data/${VERSION}/${SYSTEM}/oakctl"
  curl "${EXECUTABLE_URL}" >"${OAKCTL_BIN_PATH}"
  chmod +x "${OAKCTL_BIN_PATH}"
}

check_path() {
  if [[ ":${PATH}:" != *":${OUT_BIN_PATH}:"* ]]; then
    echo -e "${ORANGE}WARN${NC}: ${OUT_BIN_PATH} is not in your \$PATH"
  fi
}

get_system

OAKCTL_PATH="${HOME}/.local/share/oakctl"

if [[ $SYSTEM =~ ^darwin ]]; then
  OAKCTL_PATH="${HOME}/Library/Application Support/com.luxonis.oakctl"
fi

OAKCTL_BIN_PATH="${OAKCTL_PATH}/oakctl"
OAKCTL_ADDRESS="https://oakctl-releases.luxonis.com"
OUT_BIN_PATH="/usr/bin"
if [[ $SYSTEM =~ ^darwin ]]; then
  OUT_BIN_PATH="/usr/local/bin"
fi

check_installed
download_version
download_oakctl

"$OAKCTL_BIN_PATH" self-update

check_path
