###
# ~~~~~~licensing~~~~~~
# htpasswd
# ==========
# Copyright (C) 2020 - 2025 EmDev LLC
# ==========
# You may not use this file except in accordance with the License Terms of the Copyright
# Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
# rights to the Software and any copies are the property of the Copyright Holder. Unless
# it is explicitly allowed the Copyright Holder, the User is prohibited from using the
# Software for commercial purposes to provide services to third parties.
# 
# The Copyright Holder hereby declares that the Software is provided on an "AS IS".
# Under no circumstances does the Copyright Holder guarantee or promise that the
# Software provided by him will be suitable or not suitable for the specific purposes
# of the User, that the Software will meet all commercial and personal subjective
# expectations of the User, that the Software will work properly, without technical
# errors, quickly and uninterruptedly.
# 
# Under no circumstances shall the Copyright Holder or its Affiliates is not liable
# to the User for any direct or indirect losses of the User, his expenses or actual
# damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
# or damage to data, property, etc.
# ~~~~~~/licensing~~~~~~
###
#!/bin/bash 
KARAF_HOST_NAMES=("http://192.168.122.93:9091"  "http://192.168.122.94:9091")
HTPASSWD_PATH=/htpasswd
CHECKSUM_PATH=$HTPASSWD_PATH/checksum
HTPASSWD_STORAGE=/etc/nginx/htpasswd
LOGFILE="htpasswd-sync.log"
TIMESTAMP=`date "+%Y-%m-%d %H:%M:%S"`

currentChecksum=`md5sum $HTPASSWD_STORAGE | awk '{ print $1 }'`

log(){
    echo "$TIMESTAMP $1" >> $LOGFILE
}

#download actual checksum from karaf
for actualHost in ${KARAF_HOST_NAMES[*]}; do
	wget -O checksum $actualHost$CHECKSUM_PATH
	newChecksum=`cat checksum`
	rm checksum
	if [[ -n $newChecksum ]]
	then
		log "checksum received from host $actualHost"
		break
	else
		log "host $actualHost did not give checksum data"
	fi
done

log "newChecksum $newChecksum"
log "currentChecksum $currentChecksum"

if [[ -n $newChecksum ]] && { [[ -z $currentChecksum ]] || [ $currentChecksum != $newChecksum ]; };
then
    wget -O htpasswd $actualHost$HTPASSWD_PATH
    sudo mv htpasswd $HTPASSWD_STORAGE
    sudo chmod 644 $HTPASSWD_STORAGE
    sudo chown root:root $HTPASSWD_STORAGE
    sudo systemctl reload nginx
    log ">>>>>>>>>>>>>>>>> Htpasswd updated"
else
	if [[ -n $newChecksum ]]
	then
		log ">>>>>>>>>>>>>>>>> Htpasswd is up to date"
	else
		log ">>>>>>>>>>>>>>>>> Script finished with error: new checksum not received!"
		#error action
	fi
fi
