#!/bin/sh

# ------------------------------
# -- CA bundle update script
# --
# -- Version 1.3
# -- Yuri Voinov (c) 2014,2017
# ------------------------------

# Variables
BASE="/usr/local/squid/etc"
DEFAULT_FILE="ca-bundle.crt"
ADD_FILE="add_certs.pem"
CA_BUNDLE_SOURCE="https://raw.githubusercontent.com/bagder/ca-bundle/master/$DEFAULT_FILE"
DEFAULT_DEST="$BASE/ca-bundle.crt"
TMP_DIR="/tmp"
#WGET_OPTS="--no-proxy"
#WGET_OPTS="gzip"
WGET_OPTS="--no-check-certificate"

CAT=`which cat`
CUT=`which cut`
ECHO=`which echo`
GZCAT=`which gzcat`
ID=`which id`
SVCADM=`which svcadm`

# Subroutines
root_check ()
{
 if [ ! `$ID | $CUT -f1 -d" "` = "uid=0(root)" ]; then
  $ECHO "ERROR: You must be super-user to run this script."
  exit 1
 fi
}

help ()
{
 $ECHO "update_ca.sh - update Mozilla's CA bundle file."
 $ECHO "	-d dir	use destination to ouptut."                                  
 $ECHO " 	default: $DEFAULT_DEST"
 exit 1
}

# Main
root_check

# Check command line
while test $# -ne 0; do
	case $1 in
	-d|-D)
	 if test $# -eq 1; then 
          $ECHO "Need argument for -d"; 
          exit 1
         fi
	 DIR="$2"
	 shift
	 ;;
	-h|-H)
         help
	;;
	esac
	shift
done

if [ -z "$1" ]; then
 DIR="$DEFAULT_DEST"
fi

WGET=`which wget`
if [ -z "$WGET" ]; then
 $ECHO "Wget not found. If installed, add path to PATH environment variable."
 exit 1
fi
$ECHO "Wget found: $WGET"

$ECHO "CA bundle file downloading..."
if [ "$WGET_OPTS" = "gzip" ]; then
 $WGET -O $TMP_DIR/$DEFAULT_FILE".gz" "$CA_BUNDLE_SOURCE"
 $GZCAT $TMP_DIR/$DEFAULT_FILE".gz" > $DIR
elif [ "$WGET_OPTS" = "--no-proxy" -o "$WGET_OPTS" = "--no-check-certificate" ]; then
 $WGET $WGET_OPTS -O "$DIR" "$CA_BUNDLE_SOURCE"
elif [ -z "$WGET_OPTS" ]; then
 $WGET -O "$DIR" "$CA_BUNDLE_SOURCE"
else
 $ECHO "ERROR: WGET_OPTS parameter must be empty or --no-proxy or gzip or --no-check-certificate. Exiting..."
 exit 1
fi

retcode=`$ECHO $?`
case "$retcode" in
 0) $ECHO "Done.";;
 *) $ECHO "Can not download." && exit 1;;
esac

# If exists additional CA's file, concatenate it to CA bundle
if [ -f "$BASE/$ADD_FILE" ]; then
 $ECHO "Additional CA exists. Adding..."
 $CAT $BASE/$ADD_FILE>>$DIR
 $ECHO "Done."
fi

$SVCADM refresh svc:/network/squid:default

exit 0
##