#!/bin/bash
# info: add password protection to web domain statistics
# options: USER DOMAIN STATS_USER STATS_PASSWORD
#
# The call is used for securing the web statistics page.


#----------------------------------------------------------#
#                    Variable&Function                     #
#----------------------------------------------------------#

# Argument defenition
user=$1
domain=$(idn -t --quiet -u "$2" )
stats_user=$3
stats_pass=$4

# Includes
source $VESTA/func/main.sh
source $VESTA/func/domain.sh
source $VESTA/conf/vesta.conf

# Hiding password
A4='******'
EVENT="$DATE $TIME $SCRIPT $A1 $A2 $A3 $A4 $A5 $A6 $A7 $A8 $A9"


#----------------------------------------------------------#
#                    Verifications                         #
#----------------------------------------------------------#

check_args '4' "$#" 'USER DOMAIN STATS_USER STATS_PASS'
validate_format 'user' 'domain' 'stats_user' 'stats_pass'
is_system_enabled "$WEB_SYSTEM" 'WEB_SYSTEM'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"
is_object_valid 'web' 'DOMAIN' "$domain"
is_object_unsuspended 'web' 'DOMAIN' "$domain"


#----------------------------------------------------------#
#                       Action                             #
#----------------------------------------------------------#

# Definining statistic dir
stats_dir="$HOMEDIR/$user/web/$domain/stats"

# Adding htaccess file
echo "AuthUserFile $stats_dir/.htpasswd
AuthName \"Web Statistics\"
AuthType Basic
Require valid-user" > $stats_dir/.htaccess

# Generating htaccess user and password
rm -f $stats_dir/.htpasswd
htpasswd -bc $stats_dir/.htpasswd "$stats_user" "$stats_pass" &>/dev/null
stats_crypt=$(grep $stats_user: $stats_dir/.htpasswd |cut -f 2 -d :)

#----------------------------------------------------------#
#                       Vesta                              #
#----------------------------------------------------------#

# Adding stats user in config
update_object_value 'web' 'DOMAIN' "$domain" '$STATS_USER' "$stats_user"
update_object_value 'web' 'DOMAIN' "$domain" '$STATS_CRYPT' "$stats_crypt"

# Logging
log_history "added password protection for web stats on $domain"
log_event "$OK" "$EVENT"

exit
