#!/bin/sh

echo
echo "Welcome to ngxpasswd utility."
echo "We're about to create a password file."
echo

cd /passwds || exit 1

while [ "$NAME" == "" ]; do
    read -p "Name: " NAME
done

if [ -f "/passwds/$NAME.htpasswd" ]; then
    echo "ERROR: /passwds/$NAME.htpasswd already exists."
    exit 1
fi

while [ "$USER" == "" ]; do
    read -p "User: " USER
done

read -p "Password (leave blank to generate one): " PASSWORD

if [ "$PASSWORD" == "" ]; then
    echo "Password was not defined, generating a random one..."
    PASSWORD=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 20 | head -n 1)
elif [ ${#PASSWORD} -le 6 ]; then
    echo "WARNING: Non-secure password."
fi

echo -n $USER:$(openssl passwd -apr1 $PASSWORD) >> $NAME.htpasswd
chown $UID:$GID $NAME.htpasswd
chmod 640 $NAME.htpasswd

echo
echo  "A new password file has been saved to /passwds/$NAME.htpasswd :"
echo  "- Service  :  $NAME"
echo  "- User     :  $USER"
echo  "- Password :  $PASSWORD"
echo

if [ -f "/sites-enabled/$NAME.conf" ] && grep -q '#auth' /sites-enabled/$NAME.conf; then
    echo "vhost at /sites-enabled/$NAME.conf detected."

    while [[ "$ADD" !=  "y" && "$ADD" != "n" ]]; do
        read -p "Add authentication to $NAME.conf? [y/n]: " ADD
    done

    if [ "$ADD" == "y" ]; then
        cd /etc/nginx/conf
        sed -i -e 's/#auth/auth/g' -e "s/<NAME>/$NAME/g" /sites-enabled/$NAME.conf
        echo "Automatically added, please verify. Otherwise follow these instructions."
        echo
    fi
fi

echo  "Paste this to your vhost in order to enable auth :"
echo  "        auth_basic \"Who's this?\";"
echo  "        auth_basic_user_file /passwds/$NAME.htpasswd;"
echo

if [ "$ADD" == "y" ]; then
    while [[ "$RELOAD" !=  "y" && "$RELOAD" != "n" ]]; do
        read -p "Reload nginx now? [y/n]: " RELOAD
    done

    if [ "$RELOAD" == "y" ]; then
        su-exec $UID:$GID nginx -s reload
        echo "nginx successfully reloaded."
    else
        echo "Restart manually nginx to enable authentication."
    fi
fi

exit 0