#!/usr/bin/env bash
{ set +x; } 2>/dev/null

usage() {
    echo "usage: $(basename $0) app" 1>&2
    [ "$1" = "-h" ] || [ "$1" = "--help" ]; exit
}

[ "$1" = "-h" ] || [ "$1" = "--help" ] && usage "$@"

[[ $# != 1 ]] && usage

# name/bundleID
lsappinfo="$(lsappinfo info -only pid "$1" 2> /dev/null)"
[[ -n $lsappinfo ]] && { echo "$lsappinfo" | awk '{split($0,a,"=");print a[2]}'; exit; }

app_lower="$(echo "$1" | awk '{print tolower($0)}')"
LC_ALL=C
shopt -s nocasematch
matches="$(ps -Axo pid,command | grep ".app/Contents/MacOS/" | grep -i "$1")"

[[ -n "$matches" ]] && while IFS= read l; do
    [[ "$l" == *"/Contents/MacOS/"*/* ]] && continue # exclude nested apps/services
    [ -e "$1" ] && ! [ -e "$1/Contents/MacOS" ] && continue # exclude not app paths
    pid="$(echo $l | awk '{print $1}')"
    [[ "$l" == *"$1"/Contents/MacOS/* ]] && echo $pid && continue
    [[ "$l" == *"$1".app/Contents/MacOS/* ]] && echo $pid && continue
done <<< "$matches";:
