setup-hostname.in 1.28 KB
Newer Older
1 2 3 4 5 6 7
#!/bin/sh

PROGRAM=setup-hostname
PREFIX=

. $PREFIX/lib/libalpine.sh

8
usage() {
9 10
	cat <<-__EOF__
		usage: setup-hostname [-h] [HOSTNAME]
11

12
		Sets the system hostname.
13

14 15
		options:
		 -h  Show this help
16

17 18
		Sets hostname to HOSTNAME or prompt if unspecified.
	__EOF__
19
	exit 1
20 21 22
}


23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
# http://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names
valid_hostname() {
	# check length
	if [ $(echo "$1" | wc -c) -gt 63 ]; then
		echo "Hostname '$1' is too long."
		return 1
	fi
	# check that it only contains valid chars
	if ! [ -z "$(echo $1 | sed 's/[0-9a-z-]//g')" ]; then
		echo "Hostname must only contain letters (a-z), digits (0-9) or -"
		return 1
	fi
	# must not start with -
	case "$1" in
		-*) echo "Hostname must not start with a '-'"; return 1;;
	esac
	return 0
}

42
while getopts "hn:" opt; do
43
	case $opt in
44
		h) usage;;
45
		n) name="$OPTARG";;
46
	esac
47
done
48
shift $(( $OPTIND - 1 ))
49 50
if [ -z "$name" ] && [ $# -eq 1 ]; then
	name="$1"
51
fi
52

53 54 55 56 57 58 59
# if name is set, then we run non-interactively
if [ -n "$name" ] && ! valid_hostname "$name"; then
	exit 1
fi

HOST="$name"
while [ -z "$name" ]; do
60
	HOST=$(hostname)
61 62
	echon "Enter system hostname (short form, e.g. 'foo') [$HOST]: "
	default_read HOST "$HOST"
63 64 65 66
	if valid_hostname "$HOST"; then
		break
	fi
done
67 68 69

mkdir -p "$ROOT/etc"
echo "$HOST" > "$ROOT/etc/hostname"