#!/bin/sh
set -eu

if [ "${1:-}" = "--version" ] || [ "${1:-}" = "-v" ]; then
  echo "1.0.44"
  exit 0
fi

uid=$(id -u)
if [ -z "${DISPLAY:-}" ]; then
  export DISPLAY=":0"
fi
if [ -z "${XAUTHORITY:-}" ] && [ -f "$HOME/.Xauthority" ]; then
  export XAUTHORITY="$HOME/.Xauthority"
fi

if [ -z "${XDG_RUNTIME_DIR:-}" ] && [ -d "/run/user/$uid" ]; then
  export XDG_RUNTIME_DIR="/run/user/$uid"
fi

if [ -n "${XDG_RUNTIME_DIR:-}" ]; then
  if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ] && [ -S "$XDG_RUNTIME_DIR/bus" ]; then
    export DBUS_SESSION_BUS_ADDRESS="unix:path=$XDG_RUNTIME_DIR/bus"
  fi
  if [ -z "${PULSE_SERVER:-}" ] && [ -S "$XDG_RUNTIME_DIR/pulse/native" ]; then
    export PULSE_SERVER="unix:$XDG_RUNTIME_DIR/pulse/native"
  fi
fi

cache_root="${XDG_CACHE_HOME:-$HOME/.cache}"
tmp_dir="$cache_root/nubem/tmp"
mkdir -p "$tmp_dir"
chmod 700 "$tmp_dir" 2>/dev/null || true
export TMPDIR="$tmp_dir"
export TMP="$tmp_dir"
export TEMP="$tmp_dir"
unset ELECTRON_RUN_AS_NODE

self=$(readlink -f "$0" 2>/dev/null || realpath "$0")
app_dir=$(dirname "$self")
if [ "${NUBEM_FOREGROUND:-}" = "1" ]; then
  exec "$app_dir/nubem-share" "$@"
fi

if command -v setsid >/dev/null 2>&1; then
  setsid -f "$app_dir/nubem-share" "$@" >/dev/null 2>&1
else
  nohup "$app_dir/nubem-share" "$@" >/dev/null 2>&1 &
fi
