#! /bin/bash

# Sign a DSA generated by gen-D{L,S}A
# 
# This allows for any number of headers below the regular 3 that
# gen-DSA generates (From, To, Subject).
# 
# This can be useful if the advisory contains non-ASCII characters,
# like in first and last names for credits, and we need to send it as
# UTF-8. In that case, the signature will still be OK, and all the
# headers retained, even if we manually added those two to the DSA:
#
#   Content-Transfer-Encoding: 8bit
#   Content-type: text/plain; charset=UTF-8
#
# Copyright (C) 2016 Sebastien Delafond <seb@debian.org>
#
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This file is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this file.  If not, see <https://www.gnu.org/licenses/>.

set -e

usage() {
  echo "Usage: $0 </path/to/DSA-nnnn-m>"
  echo "  this will create /path/to/DSA-nnnn-m.signed"
}

if [[ $# != 1 ]] ; then
  usage
  exit 1
elif [[ $1 == "-h" ]] || [[ $1 == "--help" ]] ; then
  usage
  exit 0
fi

dsa=$1
signed_dsa=${dsa}.signed

# figure out the offset for actual DSA text, after headers
n=$(awk '/^$/ {print NR+1 ; exit}' $dsa)

# crude check for an unedited template: unreplaced $VARIABLES
# (e.g. $bookworm_VERSION) or default $TEXT leftovers should never be
# signed: "text goes here" (0 or 1 CVE), "Brief introduction" with
# bare "Description" lines (multiple CVEs, cf. DSA-6584-1), or "The
# CVE ids will be listed here when --save'ing"
template_re='\$[A-Za-z_]+|text goes here|^Brief introduction[[:space:]]*$|^[[:space:]]+Description[[:space:]]*$|listed here when'
if tail -n +"$n" "$dsa" | grep -qE "$template_re" ; then
  echo "warning: $dsa looks like an unmodified advisory template:" >&2
  tail -n +"$n" "$dsa" | grep -nE "$template_re" >&2
  read -r -p "sign it anyway? [y/N] " reply
  [[ $reply == [yY]* ]] || exit 1
fi

# create empty destination file with same permissions as the source
:> $signed_dsa
chmod --reference=$dsa $signed_dsa

# keep headers, and sign the content
{ head -n $(($n - 1)) $dsa ; tail -n +$n $dsa | gpg --clearsign ; } >| $signed_dsa
