]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - cmd/zgenhostid/zgenhostid
make spa_stats.c common
[FreeBSD/FreeBSD.git] / cmd / zgenhostid / zgenhostid
1 #!/usr/bin/env bash
2
3 # Emulate genhostid(1) available on RHEL/CENTOS, for use on distros
4 # which do not provide that utility.
5 #
6 # Usage:
7 #    zgenhostid
8 #    zgenhostid <value>
9 #
10 # If /etc/hostid already exists and is size > 0, the script exits immediately
11 # and changes nothing.  Unlike genhostid, this generates an error message.
12 #
13 # The first form generates a random hostid and stores it in /etc/hostid.
14 # The second form checks that the provided value is between 0x1 and 0xFFFFFFFF
15 # and if so, stores it in /etc/hostid.  This form is not supported by
16 # genhostid(1).
17
18 hostid_file=/etc/hostid
19
20 function usage {
21         echo "$0 [value]"
22         echo "If $hostid_file is not present, store a hostid in it." >&2
23         echo "The optional value must be an 8-digit hex number between" >&2
24         echo "1 and 2^32-1.  If no value is provided, a random one will" >&2
25         echo "be generated.  The value must be unique among your systems." >&2
26 }
27
28 # hostid(1) ignores contents of /etc/hostid if size < 4 bytes.  It would
29 # be better if this checked size >= 4 bytes but it the method must be
30 # widely portable.
31 if [ -s $hostid_file ]; then
32         echo "$hostid_file already exists.  No change made." >&2
33         exit 1
34 fi
35
36 if [ -n "$1" ]; then
37         host_id=$1
38 else
39         # $RANDOM goes from 0..32k-1
40         number=$((((RANDOM % 4) * 32768 + RANDOM) * 32768 + RANDOM))
41         host_id=$(printf "%08x" $number)
42 fi
43
44 if egrep -o '^0{8}$' <<< $host_id >/dev/null 2>&1; then
45         usage
46         exit 2
47 fi
48
49 if ! egrep -o '^[a-fA-F0-9]{8}$' <<< $host_id >/dev/null 2>&1; then
50         usage
51         exit 3
52 fi
53
54 a=${host_id:6:2}
55 b=${host_id:4:2}
56 c=${host_id:2:2}
57 d=${host_id:0:2}
58
59 echo -ne \\x$a\\x$b\\x$c\\x$d > $hostid_file
60
61 exit 0