#!/bin/bash

set -x
# INPUT

VALIDCA_URL="https://validca.libriciel.fr/"
VALIDCA_PARENT_DIR="/etc/apache2/ssl"

if [ -n "$1" ];
then
	VALIDCA_PARENT_DIR=$1
else
  NUMBER_OF_HTTPD_USERS=0
  if id "apache" >/dev/null 2>&1;
  then
    NUMBER_OF_HTTPD_USERS=$((NUMBER_OF_HTTPD_USERS+1))
    VALIDCA_PARENT_DIR="/etc/httpd/ssl"
  fi

  if id "www-data" >/dev/null 2>&1;
  then
    NUMBER_OF_HTTPD_USERS=$((NUMBER_OF_HTTPD_USERS+1))
    VALIDCA_PARENT_DIR="/etc/apache2/ssl"
  fi

  if id "nginx" >/dev/null 2>&1;
  then
    NUMBER_OF_HTTPD_USERS=$((NUMBER_OF_HTTPD_USERS+1))
    VALIDCA_PARENT_DIR="/etc/nginx/ssl"
  fi

  if [ $NUMBER_OF_HTTPD_USERS -gt 1 ];
  then
    echo "$NUMBER_OF_HTTPD_USERS httpd users found"
    exit -5
  fi

fi

VALIDCATGZ=validca.tar.gz
VALIDCAMD5=validca.md5sum

rm -f "$VALIDCA_PARENT_DIR/$VALIDCATGZ"
rm -f "$VALIDCA_PARENT_DIR/$VALIDCAMD5"

mkdir -p $VALIDCA_PARENT_DIR
cd $VALIDCA_PARENT_DIR
wget -q "$VALIDCA_URL/$VALIDCATGZ"
if [ ! -e "$VALIDCA_PARENT_DIR/$VALIDCATGZ" ]
then
	echo "Le fichier $VALIDCA_PARENT_DIR/$VALIDCATGZ n'existe pas"
	exit -1;
fi


wget -q "$VALIDCA_URL/$VALIDCAMD5"
if [ ! -e "$VALIDCA_PARENT_DIR/$VALIDCAMD5" ]
then
	echo "Le fichier $VALIDCA_PARENT_DIR/$VALIDCAMD5 n'existe pas"
    exit -2;
fi

MD5=`md5sum "$VALIDCA_PARENT_DIR/$VALIDCATGZ" | awk '{print $1}'`
echo "$MD5"

if [ -z "$MD5" ]
then
	echo "PROBLEME MD5SUM null"
	exit -3;
fi

if [ "$MD5" != `cat "$VALIDCA_PARENT_DIR/$VALIDCAMD5"` ]
then
	echo "PROBLEME MD5SUM DIFFERENT DE CELUI TELECHARGE";
	exit -4;
fi

rm -rf "$VALIDCA_PARENT_DIR/validca-old"
rm -rf "$VALIDCA_PARENT_DIR/validca-new"
mkdir -p "$VALIDCA_PARENT_DIR/validca-new"


cd "$VALIDCA_PARENT_DIR"
tar -xzf "$VALIDCA_PARENT_DIR/$VALIDCATGZ" -C "$VALIDCA_PARENT_DIR/validca-new/"
c_rehash "$VALIDCA_PARENT_DIR/validca-new/validca/"


if [ -e "$VALIDCA_PARENT_DIR/validca" ]
then
    mv "$VALIDCA_PARENT_DIR/validca" "$VALIDCA_PARENT_DIR/validca-old" && mv "$VALIDCA_PARENT_DIR/validca-new/validca" "$VALIDCA_PARENT_DIR"
else
    mv "$VALIDCA_PARENT_DIR/validca-new/validca" "$VALIDCA_PARENT_DIR"
fi

rm -rf "$VALIDCA_PARENT_DIR/validcargs-old"
rm -rf "$VALIDCA_PARENT_DIR/validcargs-new"
mkdir -p "$VALIDCA_PARENT_DIR/validcargs-new"

cp -f $VALIDCA_PARENT_DIR/validca/RGS*.pem $VALIDCA_PARENT_DIR/validcargs-new
cp -f $VALIDCA_PARENT_DIR/validca/*.crl $VALIDCA_PARENT_DIR/validcargs-new
cp -f $VALIDCA_PARENT_DIR/validca/*dgfip* $VALIDCA_PARENT_DIR/validcargs-new
c_rehash $VALIDCA_PARENT_DIR/validcargs-new

if [ -e "$VALIDCA_PARENT_DIR/validcargs" ]
then
    mv "$VALIDCA_PARENT_DIR/validcargs" "$VALIDCA_PARENT_DIR/validcargs-old" && mv "$VALIDCA_PARENT_DIR/validcargs-new" "$VALIDCA_PARENT_DIR/validcargs"
else
    mv "$VALIDCA_PARENT_DIR/validcargs-new" "$VALIDCA_PARENT_DIR/validcargs"
fi


exit 0
