#!/bin/sh

# Removes leading and trailing blank lines.  Within the file, replaces multiple
# blank lines by one blank line.  Lines containing only whitespace count as
# blank at beginning and end of file, but not within file.  (TODO: make the
# behavior consistent.)
#
# If given a filename, rewrites the file.
# Otherwise, reads from stdin and outputs to stdout.
#
# Rewriting a file writes the new contents to a temporary file in the file's
# directory, then renames that over the file.  Therefore, rewriting requires
# write permission on the directory, and other hard links to the file still
# refer to the old contents.  A symbolic link is not replaced by a regular
# file, and the file's permissions and ownership are preserved; a file whose
# owner cannot be preserved is not rewritten at all.  Access control lists and
# extended attributes are not preserved.

# 1. Determine the input source.
# If $1 exists, read from that file; otherwise, read from stdin.
input="${1:-/dev/stdin}"

# Reject an input file that cannot be read or rewritten in place.  Without this
# check, the file would be created or truncated below.
if [ -n "$1" ]; then
  if [ ! -e "$1" ]; then
    echo "squeeze-blank-lines: no such file: $1" >&2
    exit 2
  fi
  if [ ! -f "$1" ]; then
    echo "squeeze-blank-lines: not a regular file: $1" >&2
    exit 2
  fi
  if [ ! -r "$1" ]; then
    echo "squeeze-blank-lines: cannot read file: $1" >&2
    exit 2
  fi
fi

# 2. Read the data, squeezing internal blank lines.  Read it all before writing
# anything, and check for failure, so that a read error does not destroy the
# contents of an in-place-edited file.  (Reading and writing are separate steps
# because `sh` has no `pipefail`, so a failure of `cat` in the middle of a
# pipeline would go unnoticed.)
squeezed_data=$(cat -s "$input")
status=$?
if [ "$status" -ne 0 ]; then
  echo "squeeze-blank-lines: failed to read $input" >&2
  exit "$status"
fi

# 3. Remove leading blank lines, then remove trailing blank lines.  Each `sed`
# is run as a separate command whose status is checked, rather than as one
# pipeline, for the reason given in step 2:  `sh` has no `pipefail`, so a
# failure of the first `sed` of a pipeline would go unnoticed and its truncated
# output would be written over the input file.
processed_data=$(printf '%s\n' "$squeezed_data" | sed '/[^[:blank:]]/,$!d')
status=$?
if [ "$status" -ne 0 ]; then
  echo "squeeze-blank-lines: failed to process $input" >&2
  exit "$status"
fi

processed_data=$(printf '%s\n' "$processed_data" \
  | sed -e :a -e '/^[[:space:]]*$/{$d;N;ba' -e '}')
status=$?
if [ "$status" -ne 0 ]; then
  echo "squeeze-blank-lines: failed to process $input" >&2
  exit "$status"
fi

# 4. Determine the output destination.
# When the input is empty or entirely blank, $processed_data is empty; emit
# nothing rather than a single blank line (command substitution stripped the
# trailing newline, so printf would otherwise re-add one).
if [ -n "$1" ]; then
  # If a file was provided, write back to it (in-place).  Write the new
  # contents to a temporary file in the same directory, then rename it over
  # the input file.  The rename is atomic, so a signal or a full filesystem
  # leaves the original file intact rather than truncated or half-written.

  # If the input is a symbolic link, rewrite the file it refers to, rather
  # than replacing the link by a regular file.  `readlink -f` would resolve
  # the whole chain of links in one step, but it is a GNU extension that BSD
  # and older macOS lack.  Resolving only the last component is enough:  the
  # goal is to name a regular file, not to canonicalize the directories
  # leading to it.
  outfile="$1"
  links=0
  while [ -L "$outfile" ]; do
    # Give up rather than loop forever on a cycle of symbolic links.  The
    # `-e` test above usually rejects such a cycle first, because the kernel
    # refuses to resolve it; this is in case some kernel does not.
    if [ "$links" -ge 40 ]; then
      echo "squeeze-blank-lines: too many levels of symbolic links: $1" >&2
      exit 2
    fi
    links=$((links + 1))
    target=$(readlink -- "$outfile")
    if [ -z "$target" ]; then
      echo "squeeze-blank-lines: cannot resolve symbolic link: $1" >&2
      exit 2
    fi
    case "$target" in
      /*) outfile="$target" ;;
      # A relative target is relative to the directory of the link.
      *) outfile="$(dirname -- "$outfile")/$target" ;;
    esac
  done
  outdir=$(dirname -- "$outfile")

  tmpfile=$(mktemp -- "$outdir/squeeze-blank-lines.XXXXXX")
  status=$?
  if [ "$status" -ne 0 ]; then
    echo "squeeze-blank-lines: failed to create a temporary file in $outdir;" \
      "rewriting $1 requires write permission on its directory" >&2
    exit "$status"
  fi
  # Remove the temporary file if this script is interrupted.  The handlers
  # for the signals exit, so that an interrupted write is never renamed over
  # the input file.  XFSZ is listed because it is what a file-size limit
  # (`ulimit -f`) raises.
  trap 'rm -f -- "$tmpfile"' EXIT
  trap 'rm -f -- "$tmpfile"; exit 2' HUP INT TERM XFSZ

  if [ -n "$processed_data" ]; then
    printf '%s\n' "$processed_data" > "$tmpfile"
  else
    : > "$tmpfile"
  fi
  status=$?
  if [ "$status" -ne 0 ]; then
    echo "squeeze-blank-lines: failed to write $1" >&2
    exit "$status"
  fi

  # Give the temporary file the input file's ownership and permissions.  This
  # is done after writing the contents, because the input file may be
  # read-only:  a user who owns a read-only file, or who can write its
  # directory, may rewrite it.
  # `stat`'s options for this differ among implementations:  `-c` is GNU and
  # BusyBox, `-f` is BSD and macOS.
  file_mode=$(stat -c '%a' -- "$outfile" 2> /dev/null \
    || stat -f '%Lp' -- "$outfile" 2> /dev/null)
  if [ -z "$file_mode" ]; then
    echo "squeeze-blank-lines: failed to read the permissions of $1" >&2
    exit 2
  fi
  file_owner=$(stat -c '%u:%g' -- "$outfile" 2> /dev/null \
    || stat -f '%u:%g' -- "$outfile" 2> /dev/null)
  if [ -z "$file_owner" ]; then
    echo "squeeze-blank-lines: failed to read the ownership of $1" >&2
    exit 2
  fi
  tmp_owner=$(stat -c '%u:%g' -- "$tmpfile" 2> /dev/null \
    || stat -f '%u:%g' -- "$tmpfile" 2> /dev/null)
  if [ "$tmp_owner" != "$file_owner" ]; then
    # Changing the ownership fails unless the user has the privilege to do so.
    # It precedes `chmod` because it clears the setuid and setgid bits.
    chown -- "$file_owner" "$tmpfile" 2> /dev/null
    tmp_owner=$(stat -c '%u:%g' -- "$tmpfile" 2> /dev/null \
      || stat -f '%u:%g' -- "$tmpfile" 2> /dev/null)
  fi
  # The rename replaces the input file by the temporary file, so an owner that
  # could not be set would silently transfer the file to whoever ran this
  # script.  Rather than do that, refuse to rewrite the file.  (Writing to the
  # file itself, which is what this script used to do, would have failed with
  # a permission error.)  A group that could not be set is only a warning:
  # losing a group is not a change of ownership.
  if [ "${tmp_owner%:*}" != "${file_owner%:*}" ]; then
    echo "squeeze-blank-lines: not rewriting $1, because its owner" \
      "(${file_owner%:*}) cannot be preserved" >&2
    exit 2
  fi
  if [ "$tmp_owner" != "$file_owner" ]; then
    echo "squeeze-blank-lines: warning: the group of $1 changes from" \
      "${file_owner#*:} to ${tmp_owner#*:}" >&2
  fi
  if ! chmod -- "$file_mode" "$tmpfile"; then
    echo "squeeze-blank-lines: failed to set the permissions of $1" >&2
    exit 2
  fi

  if ! mv -f -- "$tmpfile" "$outfile"; then
    echo "squeeze-blank-lines: failed to write $outfile" >&2
    exit 2
  fi
elif [ -n "$processed_data" ]; then
  # Otherwise, output to stdout.
  printf '%s\n' "$processed_data"
fi
