#!/bin/bash -ue
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Reformat Markdown files via prettier, with path-munging convenience.
#
#   Default: 80-char prose wrap, in-place.
#   --check: report files that need formatting; no in-place write.
#   --print-unwrapped: emit single-line paragraphs to stdout (for Workplace,
#     which renders source linebreaks as <br>); no in-place write.
#
# To pass flags to prettier verbatim, put them after `--`:
#   reformat-md foo.md -- --print-width=100

set -o pipefail

usage() {
  cat <<'EOF'
Usage: reformat-md [--check | --print-unwrapped] FILE... [-- PRETTIER_ARGS...]

Format Markdown with Prettier at 80 columns by default. The default mode writes changes.

  --check              Report files that need formatting without changing them.
  --print-unwrapped    Print single-line paragraphs without changing files.
  -h, --help           Show this help.

Run `reformat-md -- --help` to show Prettier's options.
EOF
}

if [[ $# -eq 0 ]]; then
  usage >&2
  exit 1
fi

mode="write"
files=()
passthrough=()
seen_dashdash=0

for arg in "$@"; do
  if [[ $seen_dashdash -eq 1 ]]; then
    passthrough+=("$arg")
    continue
  fi
  case "$arg" in
    --) seen_dashdash=1 ;;
    --check | --print-unwrapped)
      if [[ $mode != write && $mode != "${arg#--}" ]]; then
        echo 'reformat-md: --check and --print-unwrapped cannot be combined' >&2
        exit 2
      fi
      mode="${arg#--}"
      ;;
    -h | --help)
      usage
      exit 0
      ;;
    *)
      # Resolve relative paths to absolute so prettier finds them
      # regardless of its own working directory.
      if [[ -e "$arg" ]]; then
        files+=("$(realpath "$arg")")
      else
        files+=("$arg")
      fi
      ;;
  esac
done

if [[ $mode != write ]]; then
  for arg in "${passthrough[@]}"; do
    if [[ $arg == --write || $arg == --write=* ||
      ($arg == -* && $arg != --* && $arg == *w*) ]]; then
      echo "reformat-md: --write conflicts with --$mode" >&2
      exit 2
    fi
  done
fi

case "$mode" in
  write) mode_args=(--prose-wrap=always --print-width=80 --write) ;;
  check) mode_args=(--prose-wrap=always --print-width=80 --check) ;;
  print-unwrapped) mode_args=(--prose-wrap=never --print-width=80) ;;
esac

exec prettier "${mode_args[@]}" "${passthrough[@]}" -- "${files[@]}"
