#!/bin/bash
#
# Purpose : Mount a folder from another machine over SFTP (sshfs) and stay in
#           the foreground until it's unmounted. A systemd user service that
#           `configure storage` writes runs it at login.
#
# It runs as you, not root, so it can use your SSH keys: Bitwarden's SSH agent
# while Bitwarden is running it, as in your .bashrc, otherwise GNOME's. It
# never asks for a password, so the server has to accept one of those keys.
#
# Usage: sftp-mount <user@host:path> <mount point>

if [ $# -ne 2 ]; then
  echo "Usage: sftp-mount <user@host:path> <mount point>" >&2
  exit 2
fi

if [ -S "$HOME/.bitwarden-ssh-agent.sock" ]; then
  export SSH_AUTH_SOCK="$HOME/.bitwarden-ssh-agent.sock"
elif [ -S "${XDG_RUNTIME_DIR:-/run/user/$UID}/gcr/ssh" ]; then
  export SSH_AUTH_SOCK="${XDG_RUNTIME_DIR:-/run/user/$UID}/gcr/ssh"
fi

# A mount left behind by a crash would make sshfs fail
mountpoint -q "$2" && fusermount3 -u "$2"

# reconnect and ServerAlive* bring it back after the network drops (e.g.
# suspend); idmap=user shows your files on the server as yours here
exec sshfs -f "$1" "$2" \
  -o reconnect,ServerAliveInterval=15,ServerAliveCountMax=3 \
  -o BatchMode=yes,ConnectTimeout=15,idmap=user
