#!/bin/sh -e

# open current directory if no argument is given
open() {
  if command -v open >/dev/null 2>&1; then
    :
  else
    open() { xdg-open "$@"; }
  fi

  if command -p -- test "${#}" -eq 0; then
    command open -- "${PWD:-.}"
  else
    case "${1-}" in
    P)
      { command -p -- test "${2-}" != '' &&
        command open -- 'https://pubs.opengroup.org/onlinepubs/9799919799/utilities/'"${2-}"'.html'; } ||
        command open -- 'https://pubs.opengroup.org/onlinepubs/9799919799/idx/utilities.html'
      ;;
    p)
      { command -p -- test "${2-}" != '' &&
        command open -- 'https://pubs.opengroup.org/onlinepubs/9799919799/utilities/'"${2-}"'.html'; } ||
        command open -- 'https://pubs.opengroup.org/onlinepubs/9799919799/idx/utilities.html'
      ;;
    B)
      { command -p -- test "${2-}" != '' &&
        command open -- 'https://pubs.opengroup.org/onlinepubs/9799919799/utilities/V3_chap02.html#'"${2-}"; } ||
        command open -- 'https://pubs.opengroup.org/onlinepubs/9799919799/idx/sbi.html'
      ;;
    b)
      { command -p -- test "${2-}" != '' &&
        command open -- 'https://pubs.opengroup.org/onlinepubs/9799919799/utilities/V3_chap02.html#'"${2-}"; } ||
        command open -- 'https://pubs.opengroup.org/onlinepubs/9799919799/idx/sbi.html'
      ;;
    g)
      shift &&
        gopen "${@-}"
      ;;
    sc*)
      command open -- 'https://github.com/koalaman/shellcheck/wiki/SC'"${1#sc}"
      ;;
    SC*)
      command open -- 'https://github.com/koalaman/shellcheck/wiki/'"${1-}"
      ;;
    so*)
      # like cheat.sh's `so/q/33041363`
      command open -- 'https://stackoverflow.com/'"${1#so/}"
      ;;
    *)
      command open "${@-}"
      ;;
    esac
  fi
}

open "$*"
