#!/bin/bash

if [ ! "$(CreoleGet activer_proxy_client_mitm non 2>/dev/null)" = "oui" ]; then
    exit 0
fi

. /usr/lib/eole/diagnose.sh

FINGERPRINT_TYPE="$(CreoleGet proxy_client_mitm_fingerprint_type)"
FINGERPRINT="$(echo $FINGERPRINT_TYPE|tr a-z A-Z) FINGERPRINT=$(CreoleGet proxy_client_mitm_fingerprint)"
DEST_FILE="/usr/local/share/ca-certificates/ca_proxy.crt"

if [ -f $DEST_FILE ] && [ "$(openssl x509 -in $DEST_FILE -$FINGERPRINT_TYPE -noout -fingerprint)" = "$FINGERPRINT" ]; then
    exit 0
fi

rm -f $DEST_FILE

dir=$(mktemp -d)
cd $dir
openssl s_client -showcerts -connect eole.ac-dijon.fr:443 -proxy $(CreoleGet proxy_client_adresse):$(CreoleGet proxy_client_port) </dev/null 2>/dev/null|awk '/^-----BEGIN CERT/,/^-----END CERT/'|awk 'BEGIN {c=0;} /BEGIN CERT/{c++} { print > "cert." c ".crt"}'

for file in $(ls); do
    if [ "$(openssl x509 -in $file -$FINGERPRINT_TYPE -noout -fingerprint|tr a-z A-Z)" = "$FINGERPRINT" ]; then
        cp -a $file $DEST_FILE
        update-ca-certificates
        break
    fi
done
rm *
cd - > /dev/null
rmdir "$dir"
if [ ! -f "$DEST_FILE" ]; then
    EchoRouge "Impossible de trouver le certificat racine avec l'emprunte $FINGERPRINT"
    exit 1
fi

exit 0
