#!/bin/sh
set -eu
printf 'Alpnexa Drive Client for macOS\n'
printf 'The token will be stored in your local rclone config or macOS WebDAV mount. Revoke the token if this machine is shared, lost, or retired.\n'
printf 'Folder token: '
IFS= read -r TOKEN
if [ -z "$TOKEN" ]; then
  echo 'Missing token.' >&2
  exit 1
fi
URL="https://downloads.alpnexa.com/dav/$TOKEN/"
MOUNT="$HOME/AlpnexaDrive"
mkdir -p "$MOUNT"
if command -v rclone >/dev/null 2>&1; then
  rclone config create alpnexa_filedrive webdav url "$URL" vendor other >/dev/null
  if pgrep -f "rclone mount alpnexa_filedrive:" >/dev/null 2>&1; then
    echo 'An existing Alpnexa rclone mount appears to be running.'
  else
    rclone mount alpnexa_filedrive: "$MOUNT" --vfs-cache-mode writes --daemon
  fi
else
  echo 'rclone not found; using native macOS WebDAV mount. Native WebDAV is a basic fallback; rclone plus macFUSE is recommended for regular upload/download work.'
  if mount | grep -F " on $MOUNT " >/dev/null 2>&1; then
    echo "$MOUNT is already mounted."
  else
    mount_webdav "$URL" "$MOUNT"
  fi
fi
if [ -d "$HOME/Desktop" ]; then
  ln -sfn "$MOUNT" "$HOME/Desktop/AlpnexaDrive"
fi
echo "Mounted at $MOUNT"
echo 'Desktop shortcut: ~/Desktop/AlpnexaDrive'
