#!/usr/bin/env bash
BINARY_NAME="sm"
TARGET_DIR="$HOME/.local/bin"
BINARY_PATH="$TARGET_DIR/$BINARY_NAME"
SUBLIME_DIR="$TARGET_DIR/sublime_merge"

if [ ! -x "$BINARY_PATH" ]; then
  notify-send "📦 Installing $BINARY_NAME" "Downloading Sublime Merge..."

  mkdir -p "$TARGET_DIR"

  URL=$(curl -s "https://www.sublimemerge.com/download_thanks?target=x64-tar" | grep -oP 'https://download.sublimetext.com/sublime_merge_build_\d+_x64.tar.xz' | head -n 1)
  VERSION=$(echo "$URL" | grep -oP '\d+' | head -n 1)
  FILENAME="sublime_merge_build_${VERSION}_x64.tar.xz"

  cd "$TARGET_DIR"

  if [ ! -f "$FILENAME" ]; then
    wget -q "$URL" || {
      notify-send -u critical "Installation Failed" "Failed to download $BINARY_NAME"
      exit 1
    }

    tar -xf "$FILENAME"
  fi

  if [ ! -f "$BINARY_PATH" ]; then
    ln -s "$SUBLIME_DIR/sublime_merge" "$BINARY_PATH"
  fi

  notify-send "Installation Complete" "$BINARY_NAME has been installed successfully"
fi

exec "$BINARY_PATH" "$@"
