#!/bin/bash
# info: change vesta port
# options: port
#
# Function will change vesta port

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

# Argument definition
port=$1

if [ -z "$VESTA" ]; then
    VESTA="/usr/local/vesta"
fi

# Get current vesta port by reading nginx.conf
oldport=$(grep 'listen' $VESTA/nginx/conf/nginx.conf | awk '{print $2}' | sed "s|;||")
if [ -z "$oldport" ]; then
    oldport=8083
fi

# Includes
source $VESTA/func/main.sh

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

# Checking permissions
if [ "$(id -u)" != '0' ]; then
    check_result $E_FORBIDEN "You must be root to execute this script"
fi

check_args '1' "$#" 'PORT'
is_int_format_valid "$port" 'port number'

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

sed -i "s|$oldport;|$port;|g" $VESTA/nginx/conf/nginx.conf
sed -i "s|$oldport ssl;|$port ssl;|g" $VESTA/nginx/conf/nginx.conf
if [ -f "/etc/roundcube/plugins/password/config.inc.php" ]; then
    sed -i "s|'$oldport'|'$port'|g" /etc/roundcube/plugins/password/config.inc.php
fi
sed -i "s|'$oldport'|'$port'|g" $VESTA/data/firewall/rules.conf
$VESTA/bin/v-update-firewall
systemctl restart fail2ban.service
sed -i "s| $oldport | $port |g" /etc/iptables.rules
systemctl restart vesta

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

# Logging
log_event "$OK" "$ARGUMENTS"

exit 0;