#!/bin/sh
#
# Copyright (C) 2023 Red Hat, Inc.
#
# 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.
#
# SPDX-License-Identifier: Apache-2.0


set -u

# avoid [[ which is not POSIX sh.
if test "$#" != 1; then
  echo "$0 requires an argument."
  exit 1
fi

if test ! -f "$1"; then
  echo "file does not exist: $1"
  exit 1
fi

pnpm commitlint --edit "$1"

SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
grep -qs "^$SOB" "$1" || echo "$SOB" >>"$1"

# Catches duplicate Signed-off-by lines.

test "" = "$(grep '^Signed-off-by: ' "$1" |
  sort | uniq -c | sed -e '/^[   ]*1[    ]/d')" || {
  echo >&2 Duplicate Signed-off-by lines.
  exit 1
}
