#!/bin/bash

set -e

usage() {
    cat <<EOF
Usage: $0 <cert.p12> <cert.pem>

Transforms a .p12 file, for instance as exported by Firefox's
cerfiticate "backup" feature, into a PEM file that contains your
private key and certificate.

To export your certificate from Firefox, go to Edit|Preferences,
Advanced|Security|View Certificates, and ``Backup'' your certificate
to a file. Firefox will save it as a PKCS12 certificate. You must
enter a passphrase, which this script will prompt you for.

EOF
    exit 1
}

[ "$#" -eq 2 ] || usage

pkcs="$1"
pem="$2"

openssl pkcs12 -in "$pkcs" -nodes -out "$pem"

cat >&2 <<EOF
Private key and certificate written to $pem

Keep this file safe!

You can pass this to wget's --certificate and --private-key options,
or to curl's --cert option.

To use it with perl's LWP, set the following environment variables:

EOF

pem=$(readlink -f "$pem")

printf 'HTTPS_CERT_FILE=%q\n' "$pem"
printf 'HTTPS_KEY_FILE=%q\n' "$pem"