#!/bin/sh
#
# fullpath - echos full filepath of given file/folder
#
# ---
# source: https://github.com/yonchu/dotfiles

# if [ -e "$1" ]; then
#   case "$1" in
#     *'/'*) # we probably were already given a full path
#       ;;
#     *)
#       printf '%s/%s\n' "${PWD}" "$1"
#       ;;
#   esac
# fi

usage() {
  printf %s "\
$(basename "$0") get full filepath of given file/folder

commands:
  -a [target]   - Convert home directory path into ~.
  -s            - Resolve all symbolic links.

flags:
  -h, --help    - Display this message.
"
  exit 0
}

print_fullpath() {
  target="$1"
  if ! [ -e "${target}" ]; then
    echo "Error: Not found (${target})" 1>&2
    return 1
  fi

  if [ "${opt_h}" = "true" ]; then
    usage
  fi

  # true if file exists and is a symbolic link
  if [ "${opt_s}" = "true" ] && [ -h "${target}" ]; then
    case "$(uname -s)" in
      Darwin | FreeBSD)
        target=$(readlink -n "${target}")
        ;;
      *)
        target=$(readlink -fq "${target}")
        ;;
    esac
  fi

  fullpath=
  if [ -d "${target}" ]; then
    if [ "${opt_s}" = "true" ]; then
      fullpath=$(cd "${target}" && pwd -P)
    else
      fullpath=$(cd "${target}" && pwd -L)
    fi
  else
    dir=
    base=
    if [ "${opt_s}" = "true" ]; then
      dir=$(cd "$(dirname "${target}")" && pwd -P)
    else
      dir=$(cd "$(dirname "${target}")" && pwd -L)
    fi
    dir=${dir%/}
    base=$(basename "${target}")
    base=${base%/}
    fullpath="${dir}"/"${base}"
  fi

  # $HOME
  if [ "${opt_a}" = "true" ]; then
    fullpath_del_home=${fullpath#"${HOME}"}
    if [ "${fullpath}" != "${fullpath_del_home}" ]; then
      fullpath='~'"${fullpath_del_home:-/}"
    fi
  fi

  echo "${fullpath}"
}

# main
while getopts ash option; do
  # shellcheck disable=SC2249
  case ${option} in
    a) opt_a="true" ;;
    s) opt_s="true" ;;
    h) opt_h="true" ;;
    : | \?) usage ;;
  esac
done
shift "$((OPTIND - 1))"

if [ "$#" -eq 0 ]; then
  # set "$(pwd)" >&2
  set -- "${PWD%/}" \
    || return "${?:-1}"
fi

ret=0
for target in "$@"; do
  print_fullpath "${target}" || ret=1
done

exit "${ret}"
