#! /bin/sh

# Copyright (c) 2021 Michael Baeuerle
#
# All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, and/or sell copies of the Software, and to permit persons
# to whom the Software is furnished to do so, provided that the above
# copyright notice(s) and this permission notice appear in all copies of
# the Software and that both the above copyright notice(s) and this
# permission notice appear in supporting documentation.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
# OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY
# SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER
# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# Except as contained in this notice, the name of a copyright holder
# shall not be used in advertising or otherwise to promote the sale, use
# or other dealings in this Software without prior written authorization
# of the copyright holder.
#
# SPDX-License-Identifier: ICU

# Authenticate a cancel or supersede article against a target article
# (the one that should be replaced)
#
# The name of the file with the cancel or supersede article must be passed
# as the first parameter, the name of the file with the target article as
# the second parameter. Both articles must be in canonical format (with
# CRLF line breaks).

set -e

# Check parameters
if test $# -ne 2
then
   printf "%s\n%s\n" "Usage example: $0 supersede.txt target.txt" \
          "(Both articles must be in canonical format)"
   exit 1
fi

# Check for utilities to be installed
canlock-mhp -v >/dev/null
canlock-hfp -v >/dev/null
canlock -v >/dev/null

# Extract keys (from the cancel or supersede article)
C_KEYS=$(<$1 canlock-mhp -f "Cancel-Key" | canlock-hfp 2>/dev/null)
printf "Keys : %s\n" "$C_KEYS" 1>&2

# Extract locks (from the target article)
C_LOCKS=$(<$2 canlock-mhp -f "Cancel-Lock" | canlock-hfp 2>/dev/null)
printf "Locks: %s\n" "$C_LOCKS" 1>&2

# Verify whether at least one key matches a lock
canlock -m "$C_KEYS","$C_LOCKS"
if test $? -ne 0
then
   exit 1
fi


# EOF
