###
# ~~~~~~licensing~~~~~~
# htpasswd
# ==========
# Copyright (C) 2020 - 2021 EmDev LLC
# ==========
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#      http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ~~~~~~/licensing~~~~~~
###
# !/bin/sh 
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
