#!/usr/bin/env bash
set -o errexit
set -o pipefail

main() {
  killall -9 -q -w -r 'sshfs.+me@jool:/store/sshfs/meatballhat.+' || true
  fusermount -u ~/mnt/jool 2>/dev/null || true

  local sshfs_args=(
    me@jool:/store/sshfs/meatballhat
    ~/mnt/jool
    -o auto_unmount
    -o default_permissions
    -o reconnect
    -p 23436
    -C
  )

  local sshfs_uidfile="${HOME}/.config/sshfs-$(_hostname)-uidmap"
  if [[ -f "${sshfs_uidfile}" ]]; then
    sshfs_args=("${sshfs_args[@]}" -o uidfile="${sshfs_uidfile}")
  fi

  if [[ "${DEBUG}" == enabled ]]; then
    sshfs_args=("${sshfs_args[@]}" -f -o sshfs_debug -o LogLevel=DEBUG3)
  fi

  mkdir -p ~/mnt/jool
  sshfs "${sshfs_args[@]}"
}

_hostname() {
  hostname 2>/dev/null ||
    hostnamectl status --static 2>/dev/null ||
    echo unknown
}

main "${@}"
