#!/bin/sh

# Utilities
# --------------------------------------------------------------------- {|}

# https://leahneukirchen.org/dotfiles/bin/goog
# goog() {
#   curl -A Mozilla/4.0 -skLm 10 \
#     "http://www.google.com/search?nfpr=\&q=$(echo "$*" | tr ' ' '+')" |
#     grep -oP '\/url\?q=.+?&amp' |
#     grep -v 'google' |
#     perl -pe 's/\/url\?q=//; s/&amp//g; s/\%([[:xdigit:]]{2})/chr hex $1/ge'
#
#   if [ -n "$TMUX" ] && supports _tmux-select; then
#     _tmux-select
#   fi
# }

## check if an array contains an specific element

# This function searches an array for an exact match against the term passed
# as the first argument to the function. This function exits as soon as
# a match is found.
#
# Returns:
#   0 when a match is found, otherwise 1.
#
# Examples:
#   $ declare -a fruits=(apple orange pear mandarin)
#
#   $ _array-contains-element apple "@{fruits[@]}" && echo 'contains apple'
#   contains apple
#
#   $ if _array-contains-element pear "${fruits[@]}"; then
#       echo "contains pear!"
#     fi
#   contains pear!
#
#
# _array-contains-element() {
#     local e element="${1?}"
#     shift
#     for e in "$@"; do
#         [[ "$e" == "${element}" ]] && return 0
#     done
#     return 1
# }


# --------------------------------------------------------------------- }}}
# Filesystem
# --------------------------------------------------------------------- {|}

## pandoc functions for converting between text filetypes

if supports pandoc; then
  # Convert markdown to HTML
  md2html() {
    mkdir -p "${DOTFILES-}/cache/pandoc"
    ! [ -f "${DOTFILES}/cache/pandoc/styles.css" ] \
      && curl -Lso "${DOTFILES}/cache/pandoc/styles.css" \
        https://raw.githubusercontent.com/jez/pandoc-markdown-css-theme/master/public/css/theme.css
    ! [ -f "${DOTFILES}/cache/pandoc/highlight.css" ] \
      && curl -Lso "${DOTFILES}/cache/pandoc/highlight.css" \
        https://raw.githubusercontent.com/jez/pandoc-markdown-css-theme/master/public/css/skylighting-paper-theme.css
    ! [ -f "${DOTFILES}/cache/pandoc/template.html" ] \
      && curl -Lso "${DOTFILES}/cache/pandoc/template.html" \
        https://raw.githubusercontent.com/jez/pandoc-markdown-css-theme/master/template.html5

    pandoc \
      --katex \
      --from markdown+tex_math_single_backslash \
      --to html5+smart \
      --template="${DOTFILES}/cache/pandoc/template.html" \
      --css="${DOTFILES}/cache/pandoc/styles.css" \
      --css="${DOTFILES}/cache/pandoc/highlight.css" \
      --toc \
      --wrap=none \
      --output="${DOTFILES}/cache/pandoc/output.html" \
      "$1"

    o "${DOTFILES}/cache/pandoc/output.html"
  }
fi

## recursively search parent directory for file

# param 1: name of file or directory to find
# param 2: directory to start from (defaults to PWD)
# example: $ pfind .git
pfind() {
  test -e "${2:-${PWD}}/$1" && echo "${2:-${PWD}}" && return 0
  [ '/' = "${2:-${PWD}}" ] && return 1
  pfind "$1" "$(dirname "${2:-${PWD}}")"
}


# Networking
# --------------------------------------------------------------------- {|}

## get the pid of the prccess listening on the provided port

wtfport() {
  # local line pid pid_name

  line="$(lsof -i -P -n | grep LISTEN | grep ":$1")"
  pid=$(echo "${line}" | awk '{print $2}')
  pid_name=$(echo "${line}" | awk '{print $1}')

  # if there's nothing running, exit
  [ -z "${pid}" ] && return 0

  # output the process name to stderr so it won't be piped along
  printf "%s" "${pid_name}" >&2

  # print the process id. it can be piped, for example to pbcopy
  printf '%b\n' "${pid}"
}

# kill the process listening on the provided port
killport() { wtfport "$1" | xargs kill -9; }

# searchable process list
# shellcheck disable=2009
psg() { ps aux | grep -v grep | grep -i -e VSZ -e "$*"; }

# get top processes eating memory
psmem() {
  ps aux \
    | sort -nrk 4 \
    | awk '{a[NR]=$0}END{for(x=1;x<NR;x++){if(x==1)print a[NR];print a[x]}}' \
    | tac
}

# get top processes eating cpu
pscpu() {
  ps aux \
    | sort -nrk 3 \
    | awk '{a[NR]=$0}END{for(x=1;x<NR;x++){if(x==1)print a[NR];print a[x]}}' \
    | tac
}

# list hosts defined in ssh config
ssh_list() {
  [ -r ~/.ssh/config ] \
    && awk '$1 ~ /Host$/ {for (i=2; i<=NF; i++) print $i}' ~/.ssh/config
}

# add all ssh private keys to agent
ssh_add_all() { grep -slR "PRIVATE" ~/.ssh | xargs ssh-add; }

# display all ip addresses for this host
# shellcheck disable=SC2312
ips() {
  printf "%s\n" "Router IP (Gateway): $(
    netstat -rn | awk 'FNR == 3 {print $2}' \
      || route -n | awk 'FNR == 3 {print $2}' \
      || ip route | awk '/via/ {print $3}'
  )"

  printf "%s\n" "Local IP (Private IP): $(
    ip addr | awk '/global/ {print $2}' | cut -d'/' -f1 | head -n1 \
      || ifconfig | awk '/inet/ {print $2}' | head -n1
  )"

  printf "%s\n" "External IP (Public IP): $(
    dig +short myip.opendns.com @resolver1.opendns.com \
      || curl -s ifconfig.co \
      || curl -s checkip.amazonaws.com \
      || curl -s ipinfo.io/ip \
      || curl -s icanhazip.com \
      || curl -s smart-ip.net/myip \
      || (curl -s pasteip.me/api/cli/ && echo) \
      || curl -s http://checkip.dyndns.org \
      | grep -o '[[:digit:].]\+'
  )"
}

# Git
# --------------------------------------------------------------------- {|}

# toggle git env vars so I can use `git` instead of `dot`
tdot() {
  if [ "${GIT_WORK_TREE-}" = ~ ]; then
    unset GIT_DIR GIT_WORK_TREE
  else
    export GIT_DIR=~/.git GIT_WORK_TREE=~
  fi
}

# edit dotfiles with git plugins setup correctly
# searches with Telescope if no args are provided
# edot() {
#   EDITOR=nvim dot edit +"if !len(argv()) | execute 'lua Snacks.picker.git_files()' | endif"
# }

# open fugitive' status for the current or dotfiles repo
G() {
  # shellcheck disable=SC2312
  if [ "$(git rev-parse --is-inside-work-tree)" = "false" ]; then
    (cd && dot edit +G +only)
  else
    ${EDITOR:-vi} +G +only
  fi
}
