You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
90 lines
1.9 KiB
90 lines
1.9 KiB
#!/usr/bin/env bash
|
|
|
|
# CONSTANTS
|
|
|
|
BASEDIR=$(dirname "$0")
|
|
COMMAND=show
|
|
|
|
# FUNCTIONS
|
|
function usage {
|
|
echo "usage: $(basename "$0") [--set NEW_FQDN]"
|
|
echo " either returns the fully qualified name when pass with no argument"
|
|
echo " or define the new fully qualified name when pass --set {NEW_FQDN}"
|
|
}
|
|
|
|
function parse_options {
|
|
while [[ $# -gt 0 ]]; do
|
|
case "$1" in
|
|
'--set')
|
|
COMMAND=define
|
|
shift 1
|
|
[[ -z ${1:-} || $1 =~ ^- ]] && usage && exit 1
|
|
NEW_FQDN=$1
|
|
;;
|
|
--help | -h)
|
|
usage && exit 0
|
|
;;
|
|
*)
|
|
echo >&2 "Unknown option: $1" && usage && exit 2
|
|
;;
|
|
esac
|
|
|
|
shift 1 # Move to the next argument
|
|
done
|
|
}
|
|
|
|
function show {
|
|
hostname -f
|
|
}
|
|
|
|
function define {
|
|
if [[ $NEW_FQDN == *.* ]]; then
|
|
name=$(echo $NEW_FQDN | cut -d. -f1)
|
|
domain=${NEW_FQDN#${name}.}
|
|
if [[ -n $domain ]]; then
|
|
define_fqdn $name $domain
|
|
else
|
|
define_single $name
|
|
fi
|
|
else
|
|
define_single $NEW_FQDN
|
|
fi
|
|
}
|
|
|
|
function define_single {
|
|
local single=$1
|
|
local previous=$(hostname -f)
|
|
for i in $(grep $previous /etc/hosts | cut -f1); do
|
|
append_or_replace ^$i.* "$i\t$single" /etc/hosts >/dev/null
|
|
done
|
|
hostnamectl hostname $single
|
|
}
|
|
|
|
function define_fqdn {
|
|
local name=$1
|
|
local domain=$2
|
|
local previous=$(hostname -f)
|
|
|
|
for i in $(grep $previous /etc/hosts | cut -f1); do
|
|
append_or_replace ^$i.* "$i\t$name.$domain $name" /etc/hosts >/dev/null
|
|
done
|
|
hostnamectl hostname $name
|
|
}
|
|
|
|
function perform_command {
|
|
case $COMMAND in
|
|
show)
|
|
show
|
|
;;
|
|
define)
|
|
[[ $(id -u) != 0 ]] && echo 'require root privilege, please prepend the command with `sudo`' && exit 10
|
|
define
|
|
;;
|
|
esac
|
|
}
|
|
|
|
# MAIN
|
|
|
|
set -Eue
|
|
parse_options $*
|
|
perform_command
|