#!/bin/bash
set -eou pipefail

VERSION="0.1.0"

OS=''
case `uname` in
  Darwin*)               OS="darwin" ;;
  Linux*)                OS="linux" ;;
  MINGW*|MSYS*|CYGWIN*)  OS="windows" ;;
  *)                     echo "unsupported os: `uname`" && exit 1 ;;
esac

ARCH=`uname -m`
case "$ARCH" in
  ix86*|x86_64*)    ARCH="x86_64" ;;
  arm64*|aarch64*)  ARCH="aarch64" ;;
  *)                echo "unsupported arch: $ARCH" && exit 1 ;;
esac

if [ "$OS" = "windows" ]; then
  if [ "$ARCH" != "x86_64" ]; then
    echo "unsupported arch for windows: $ARCH" && exit 1
  fi
  if ! command -v unzip >/dev/null; then
    echo "unzip is required to install streamling" && exit 1
  fi
  ARCHIVE="streamling-$OS-$ARCH.zip"
  BINARY="streamling.exe"
else
  ARCHIVE="streamling-$OS-$ARCH.tar.gz"
  BINARY="streamling"
fi

DOWNLOAD_URL="https://github.com/goldsky-io/streamling/releases/download/v$VERSION/$ARCHIVE"

# Function to check if a directory is in PATH and writable
is_valid_install_dir() {
  [[ ":$PATH:" == *":$1:"* ]] && [ -w "$1" ]
}

INSTALL_DIR=""
USE_SUDO=""

# Check for common user-writable directories in PATH
for dir in "$HOME/bin" "$HOME/.local/bin" "$HOME/.bin"; do
  if is_valid_install_dir "$dir"; then
    INSTALL_DIR="$dir"
    break
  fi
done

# If no user-writable directory found, use system directory
if [ -z "$INSTALL_DIR" ]; then
  if [ "$OS" = "windows" ]; then
    # No sudo on windows; fall back to a user directory
    INSTALL_DIR="$HOME/bin"
    mkdir -p "$INSTALL_DIR"
  else
    INSTALL_DIR="/usr/local/bin"
    USE_SUDO=1
  fi
fi

TARGET="$INSTALL_DIR/$BINARY"
TMP_DIR=`mktemp -d`
echo "Downloading streamling from: $DOWNLOAD_URL"

if curl -fsSL --output "$TMP_DIR/$ARCHIVE" "$DOWNLOAD_URL"; then
  if [ "$OS" = "windows" ]; then
    unzip -oq "$TMP_DIR/$ARCHIVE" -d "$TMP_DIR"
  else
    tar -xzf "$TMP_DIR/$ARCHIVE" -C "$TMP_DIR"
  fi

  if [ "$USE_SUDO" = "1" ]; then
    echo "No user-writable bin directory found in PATH. Using sudo to install in $INSTALL_DIR"
    sudo mv "$TMP_DIR/$BINARY" "$TARGET"
  else
    mv "$TMP_DIR/$BINARY" "$TARGET"
  fi
  chmod +x "$TARGET"
  rm -rf "$TMP_DIR"

  echo "Successfully installed streamling to $TARGET"
else
  echo "Failed to download or install streamling. Curl exit code: $?"
  rm -rf "$TMP_DIR"
  exit 1
fi

# Warn the user if the chosen path is not in the path
if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
  echo "Note: $INSTALL_DIR is not in your PATH. You may need to add it to your PATH or use the full path to run streamling."
fi

echo "Installation complete. Check https://github.com/goldsky-io/streamling#quick-start for the next steps."
