#!/bin/bash

CHRBIN=/usr/sbin/chroot
CHRD=/chroot/proxyd


if ! [ -x /usr/bin/makepasswd ]; then
    echo "Error: makepasswd package not installed!"
    exit 7
fi


makepass() {
	echo $(makepasswd --chars=42 | tr '[:upper:]' '[:lower:]')
}

# -----------------------------------------------------

# -----------
# sanity check

if [ "$1" != "SURE" ]; then
    echo "WARNING! This script will overwrite nginx protection cookies."
    echo "If you are sure, type SURE as parameter"
    echo "Usage: $0 [SURE]"
    exit 7
fi


# -----------------------------------------------------

# changing root and debian_sys_maint passwords
newcookie=$(makepass)

echo "New protection cookie: _cms_prot_${newcookie}=1"
echo "Updating nginx configs..."

conffiles=`find $CHRD/etc/nginx/ -type f -name '*.conf'`

for conffile in $conffiles; do
	sed -i -E "s/^(.*_cms_prot_)[^\"\= ]*(.*)/\1${newcookie}\2/" $conffile
done

CAPTCHACONF=/chroot/admin/web/sys/captcha/config/config.php

if [ -f ${CAPTCHACONF} ]; then
	sed -i -E "s/^(.*_cms_prot_)[^\"\= ]*(.*)/\1${newcookie}\2/" ${CAPTCHACONF}
fi

/etc/init.d/nginx-chroot restart
