#!/bin/sh

# Creates symlinks from external application directory
# to another directory so applications are seen in
# spotlight searches and launchpad.

set -e

app_dir=""
destination_dir=""

# Parses the input arguments. If 2 arguments are passed in, then
# the first is where we search for applications (source) and the second
# argument is the destination directory for the symlinks to be placed in
#
# If one argument is passed in, then it is used as the destination directory
# and we use the default source directory.
_parse_args() {
  arg_count="$#"
  app_dir="/Volumes/M1 Mac-Mini External Drive/Applications"
  destination_dir="${HOME}/Application"
  if test "$arg_count" -eq 1; then
    destination_dir="$1"
  elif test "$arg_count" -eq 2; then
    app_dir="$1"
    destination_dir="$2"
  fi
}

# Checks if the `app_dir` exists.
_is_mounted() {
  if ! test -d "$app_dir"; then
    echo "Application directory does not exist or is not mounted" >&2
    return 1
  fi
}

# ----------------  main -------------------

main() {

  _parse_args "$@"
  test -d "${destination_dir}" || echo "Destination does not exist" >&2

  if test _is_mounted; then
    for app in "${app_dir}"/*.app; do
      destination="${destination_dir}/$(basename "${app}")"
      if test -e "${destination}"; then
        echo "Destination already exists: ${destination}. Skipping!" >&2
        continue
      fi
      # remove echo to do real work.
      echo ln -sv "${app}" "${destination}" >&2
    done
  fi
}

main "$@"
