#!/bin/bash
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you 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.
#
#
# $Id$
#
# Prevents some SHA-1 collisions to be commited
# Test fo the 320 byte prefix found on https://shattered.io/
# If the files are committed in the same transaction, svnlook
# will error out itself due to the apparent corruption in the
# candidate revision

REPOS="$1"
TXN="$2"
SVNLOOK=/usr/bin/svnlook
YEAR=$(date +%Y)

$SVNLOOK changed -t "$TXN" "$REPOS"
if [ $? -ne 0 ]; then
  echo "svnlook failed, possible SHA-1 collision" >&2
  exit 2
fi

FILES=$($SVNLOOK changed -t "$TXN" "$REPOS" | grep -Ev '^D ' | /usr/bin/awk '{print $2}')
for FILE in $FILES; do
  if [ -f $FILE ]; then
    # Check against known sha-1 collision attack.  Someone committing 2 different files with this
    # known hash collision could otherwise break the repository.
    PREFIX=$($SVNLOOK cat -t "$TXN" "$REPOS" "$FILE" | head -c320 | /usr/bin/sha1sum | cut -c-40)
    if [ "$PREFIX" = 'f92d74e3874587aaf443d1db961d4e26dde13e9c' ]; then
	  echo "known SHA-1 collision rejected" >&2
	  exit 3
    fi

    # Verify copyright year
    if [[ $FILE == */ietf/*.py || -s $FILE ]]; then
      $SVNLOOK cat -t "$TXN" "$REPOS" "$FILE" | head -n 3 | grep -q "Copyright .*IETF Trust .*$YEAR.*" || {
	  echo "
    Bad or missing copyright note in $FILE.
    Expected 'Copyright The IETF Trust ... $YEAR, All Rights Reserved',
    (or similar) at the start of the file.

    For bulk correction of copyright statements, try bin/check-copyright with
    patching:

      \$ bin/check-copyright -p \$(svn st | cut -c 9- | grep '\.py\$' ) | patch -p0

    " >&2
	  exit 3
      }
    fi
  fi
done
