#!/bin/bash
# info: update system ip
# options: [user] [ip_status]
#
# The function scans configured ip in the system and register them with vesta
# internal database. This call is intended for use on vps servers, where ip is
# set by hypervizor.


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

# Argument defenition
user=${1-admin}
ip_status=${2-shared}

# Includes
source $VESTA/conf/vesta.conf    # include for internal func
source $VESTA/func/main.sh
source $VESTA/func/ip.sh
source $VESTA/func/domain.sh


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

check_args '0' "$#" '[user] [ip_status]'
validate_format 'user' 'ip_status'
is_object_valid 'user' 'USER' "$user" "$user"


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

# Get ip list
ip_list=$(/sbin/ifconfig | grep 'inet addr:' | cut -f 2 -d : | \
    cut -f 1 -d ' '| grep -v 127.0.0.1)

# Get vesta registered ip list
vesta_ip_list=$(ls $VESTA/data/ips/)

# Defining config paths
conf='/etc/httpd/conf.d/vesta.conf'
nconf='/etc/nginx/conf.d/vesta_ip.conf'
iconf='/etc/sysconfig/network-scripts/ifcfg'
rconf='/etc/httpd/conf.d/rpaf.conf'

# Comparing each ip
for ip in $ip_list; do
    check_ip=$(echo $vesta_ip_list | grep -w "$ip")

    # Checking ip registered
    if [ -z "$check_ip" ]; then
        # Parsing additional params
        iface=$(/sbin/ifconfig |grep -B1 -w $ip |head -n 1 |cut -f 1 -d ' ')
        interface=$(echo "$iface" | cut -f 1 -d :)
        mask=$(/sbin/ifconfig |grep -w $ip |awk -F "Mask:" '{print $2}')

        # Adding vesta ip
        create_vesta_ip

        # Adding namehosting support
        namehost_ip_support

        # Creating startup script
        if [ ! -e "$iconf-$iface" ]; then
            ip_add_startup
        fi
    fi

    # TBD: revers comparation
done


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

# Updating user conf
increase_user_value "$user" '$IP_OWNED'

# Restart web server
if [ "$web_restart" = 'yes' ]; then
    $BIN/v_restart_web "$EVENT"
fi

# Logging
log_event "$OK" "$EVENT"

exit
