#!/usr/bin/bash
# info: change hostname
# options: HOSTNAME
#
# example: v-change-sys-hostname mydomain.tld
#
# This function for changing system hostname.

#----------------------------------------------------------#
#                Variables & Functions                     #
#----------------------------------------------------------#

# Argument definition
domain=$1

# Includes
# shellcheck source=/etc/hestiacp/hestia.conf
source /etc/hestiacp/hestia.conf
# shellcheck source=/usr/local/hestia/func/main.sh
source $HESTIA/func/main.sh
# load config file
source_conf "$HESTIA/conf/hestia.conf"

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

check_args '1' "$#" 'HOSTNAME'
is_format_valid 'domain'

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

hostname "$domain"

if command -v hostnamectl >/dev/null 2>&1; then
    hostnamectl set-hostname "$domain"
    echo "$domain" > /etc/hostname
else
    if [ -d "/etc/sysconfig" ]; then
        touch /etc/sysconfig/network
        if [ -z "$(grep HOSTNAME /etc/sysconfig/network)" ]; then
            echo "HOSTNAME='$domain'" >> /etc/sysconfig/network
        else
            sed -i "s/HOSTNAME=.*/HOSTNAME='$domain'/" /etc/sysconfig/network
        fi
    else
        echo "$domain" > /etc/hostname
    fi
fi

# Update Roundcube password plugin configuration
if [ -d /etc/roundcube/ ]; then
	sed -i "/password_hestia_host/c\$rcmail_config['password_hestia_host'] = '$domain';" /etc/roundcube/plugins/password/config.inc.php
fi
if [ -d /etc/rainloop/ ]; then
	sed -i "/hestia_host/c\hestia_host = \"$domain\"" /etc/rainloop/data/_data_/_default_/configs/plugin-hestia-change-password.ini
fi
if [ -d /etc/snappymail/ ]; then
	sed -i "/\"hestia_host\":/c\\\"hestia_host\": \"$domain\"," /etc/snappymail/data/_data_/_default_/configs/plugin-change-password.json
fi

if [ -f /etc/hosts ]; then
	if ! cat /etc/hosts | grep $domain > /dev/null; then
		echo "127.0.0.1 $domain" >> /etc/hosts
	fi
fi

#----------------------------------------------------------#
#                       Hestia                             #
#----------------------------------------------------------#

# Logging
$BIN/v-log-action "system" "Warning" "System" "System hostname changed (Host: $domain)."
log_event "$OK" "$ARGUMENTS"

exit
