#!/bin/bash
#
# Purpose : Mount the shared folders `configure storage` added, at login and
#           whenever the network changes (launchd starts this then).
#
# A folder whose server can't be reached, e.g. away from home, is skipped
# quietly. For an SMB share, macOS signs in with the password you saved in
# your keychain when you added it; if it can't, it asks. An SFTP folder signs
# in with your SSH keys and never asks. Either way, after a failure this
# doesn't try that folder again for an hour.
#
# Each line of the list is "<url>|<mount point>": smb://user@host/share or
# sftp://user@host[:port][/path]. SMB lines may lack the mount point, as
# macOS chooses it.
#
# Usage: storage-mount [--list]   (--list: show each folder and where it's mounted now)

# Wrapped in { ...; exit; } so bash reads the whole script up front
{

CONNECTOR="$(cd "$(dirname "$0")/.." && pwd)"
CONF_DIR="$HOME/Library/Application Support/Federated Connector"
STORAGE_CONF="$CONF_DIR/storage"
FAILED_DIR="${TMPDIR:-/tmp}/federated-storage-failed"
RETRY_AFTER=3600

source "$CONNECTOR/configure.d/lib/smb.sh" || exit 1
source "$CONNECTOR/configure.d/lib/sftp.sh" || exit 1

# Where it's mounted now, if it is
mounted_now() {
  case "$1" in
    smb://*) mounted_at "$1" ;;
    sftp://*) sftp_mounted "$2" && echo "$2" ;;
    *) return 1 ;;
  esac
}

mount_one() {
  case "$1" in
    smb://*) mount_share "$1" ;;
    sftp://*) sftp_mount "$1" "$2" > /dev/null 2>&1 ;;
  esac
}

[ -f "$STORAGE_CONF" ] || exit 0

if [ "$1" = --list ]; then
  while IFS='|' read -r url point; do
    [ -n "$url" ] || continue
    echo "$url|$(mounted_now "$url" "$point")"
  done < "$STORAGE_CONF"
  exit 0
fi

mkdir -p "$FAILED_DIR"
while IFS='|' read -r url point; do
  [ -n "$url" ] || continue
  mounted_now "$url" "$point" > /dev/null && continue
  case "$url" in
    smb://*) host="$(host_of "$url")" port=445 ;;
    sftp://*) sftp_parse "$url"; host="$SFTP_HOST" port="$SFTP_PORT" ;;
    *) continue ;;
  esac
  nc -z -G 3 "$host" "$port" > /dev/null 2>&1 || continue
  marker="$FAILED_DIR/$(echo "$url" | tr -c '[:alnum:]._-' '_')"
  if [ -f "$marker" ] && [ $(($(date +%s) - $(stat -f %m "$marker"))) -lt $RETRY_AFTER ]; then
    continue
  fi
  if mount_one "$url" "$point"; then
    rm -f "$marker"
  else
    touch "$marker"
  fi
done < "$STORAGE_CONF"
exit 0
}
