#!/bin/bash
#
# Purpose : Mount the shared folders `configure storage` added, at login and
#           whenever the network changes (launchd starts this then).
#
# A share whose server can't be reached, e.g. away from home, is skipped
# quietly. macOS signs in with the password you saved in your keychain when
# you added the share. If it can't, it asks; if you cancel, this doesn't ask
# again for an hour.
#
# Usage: storage-mount [--list]   (--list: show each share and whether it's mounted)

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

CONF_DIR="$HOME/Library/Application Support/Federated Connector"
STORAGE_CONF="$CONF_DIR/storage"
FAILED_DIR="${TMPDIR:-/tmp}/federated-storage-failed"
RETRY_AFTER=3600

source "$(cd "$(dirname "$0")/.." && pwd)/configure.d/lib/smb.sh" || exit 1

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

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

mkdir -p "$FAILED_DIR"
while IFS= read -r url; do
  [ -n "$url" ] || continue
  mounted_at "$url" > /dev/null && continue
  nc -z -G 3 "$(host_of "$url")" 445 > /dev/null 2>&1 || continue
  marker="$FAILED_DIR/$(share_key "$url" | tr '/ ' '__')"
  if [ -f "$marker" ] && [ $(($(date +%s) - $(stat -f %m "$marker"))) -lt $RETRY_AFTER ]; then
    continue
  fi
  if mount_share "$url"; then
    rm -f "$marker"
  else
    touch "$marker"
  fi
done < "$STORAGE_CONF"
exit 0
}
