#!/usr/bin/env bash
# usage:
# 1. make this file executable `chmod +x execute-in.sh`
# 2. create an alias
#   alias `command`="~/execute-in.sh `target` `command`"
#   example: alias yarn="~/execute-in.sh app/javascript yarn"

cwd=$(pwd)
target="$1"
command="$2"

if [ $(pwd | grep $target 2>&1) ]; then
  # in $target
  echo "in $target"
  echo "> $target ${@:3}"
  $command "${@:3}"
elif [ -d "$target" ]; then
  # not in $target but $target exists
  echo "> cd $target"
  cd $target
  echo "> $command ${@:3}"
  $command "${@:3}"
  cd $cwd
else
  # $target doesn't exist
  echo "$command $1 $2 doesn't exists, continuing"
  echo "> $command ${@:3}"
  $command "${@:3}"
fi