#! /bin/bash
#
# updates_create_signature
#
# This file is a modified version of "sign_update" distributed with Sparkle Updater (https://sparkle-project.org/).
#
# Modifications copyright © 2016, 2018 by Jonathan K. Bullard. All rights reserved.
#
#  This file is part of Tunnelblick.
#
#  Tunnelblick is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License version 2
#  as published by the Free Software Foundation.
#
#  Tunnelblick 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 program (see the file COPYING included with this
#  distribution); if not, write to the Free Software Foundation, Inc.,
#  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#  or see http://www.gnu.org/licenses/.

##########################################################################################
#
# Outputs a base-64-encoded signature for an update (or any file)
#
# Usage:
#
#	updates_create_signature    private_key_path    target_path
#
#		"private_key_path" is the path to a "dsa_priv.pem" file (as generated by Sparkle's generate_keys script)
#
#		"target_path" is the path of the file to be signed

##########################################################################################

# Set up and check arguments

set -e
set -o pipefail

export PATH="/bin:/sbin:/usr/sbin:/usr/bin"

if [ "$#" -ne 2 ]; then
  echo "Usage: $0 private_key update_archive"
  exit 1
fi

filename=$(basename "$1")
extension=$([[ "$filename" = *.* ]] && echo ".${filename##*.}" || echo '')
if [ "$extension" != ".pem" ] ; then
	echo "Private key file must be a '.pem' file"
	exit 1
fi

if [ ! -f "$1" ] ; then
	echo "No private key file at $1"
	exit 1
fi

readonly private_key_path="$1"

if [ ! -f "$2" ] ; then
	echo "No file to create signature for at $2"
	exit 1
fi

readonly target_path="$2"

##########################################################################################

openssl dgst -sha1 -binary < "$target_path"			\
  | openssl dgst -dss1 -sign "$private_key_path"	\
  | openssl enc  -base64
