#!/bin/bash
#
# Strips TinyPilot marker sections from a file.
#
# If the target file contains marker sections, this script removes the markers
# and any content in between them.
# If the target file doesn’t contain marker sections, running this script is a
# noop.
# If the target file contains unmatched/orphaned markers, this script fails.

# We don’t use `set -x`, because it would output every single iteration of the
# while loop when iterating through the lines of the target file, and hence
# generate a lot of noise.

# Exit on first failure.
set -e

# Exit on unset variable.
set -u

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
readonly SCRIPT_DIR
# shellcheck source=lib/markers.sh
. "${SCRIPT_DIR}/lib/markers.sh"

print_help() {
  cat << EOF
Usage: ${0##*/} [--help] TARGET_FILE
Strips TinyPilot marker sections from a file.
  TARGET_FILE   Path to file with marker sections.
  --help        Display this help and exit.
EOF
}

# Parse command-line arguments.
TARGET_FILE=''
while (( "$#" > 0 )); do
  case "$1" in
    --help)
      print_help
      exit
      ;;
    -*)
      echo "Illegal option: $1" >&2
      exit 1
      ;;
    *)
      TARGET_FILE="$1"
      shift
      ;;
  esac
done
readonly TARGET_FILE

# Ensure target file is specified.
if [[ -z "${TARGET_FILE}" ]]; then
  echo 'Input parameter missing: TARGET_FILE' >&2
  exit 1
fi

# Ensure target file exists and is a file.
if [[ ! -f "${TARGET_FILE}" ]]; then
  echo "Not a file: ${TARGET_FILE}" >&2
  exit 1
fi

# Read the original file line by line, and remove marker sections.
# This is done by iterating through the lines, and filtering out lines that are
# either markers themselves, or in between markers.
preserved_lines=()
is_in_marker_section='false'
while IFS='' read -r line; do
  if [[ "${line}" == "${MARKER_END}" ]]; then
    if ! "${is_in_marker_section}"; then
      echo 'Unmatched end marker' >&2
      exit 1
    fi
    is_in_marker_section='false'
    continue
  fi
  if "${is_in_marker_section}" || [[ "${line}" == "${MARKER_START}" ]]; then
    is_in_marker_section='true'
    continue
  fi
  preserved_lines+=("${line}")
done < "${TARGET_FILE}"

if "${is_in_marker_section}"; then
  echo 'Unmatched start marker' >&2
  exit 1
fi

# Populate preserved lines to file.
printf "%s\n" "${preserved_lines[@]}" > "${TARGET_FILE}"
