new tool: fqdn
This commit is contained in:
Executable
+90
@@ -0,0 +1,90 @@
|
||||
#!/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
|
||||
Reference in New Issue
Block a user