+#
+# Writes new hosts information to the hosts file in $s->{ConfDir}/hosts.
+# With no argument a ref to a hash of hosts is returned. Each
+# hash contains fields as specified in the hosts file. With an
+# argument a ref to a single hash is returned with information
+# for just that host.
+#
+sub HostInfoWrite
+{
+ my($s, $hosts) = @_;
+ my($gotHdr, @fld, $hostText, $contents);
+ local(*HOST_INFO);
+
+ if ( !open(HOST_INFO, "$s->{ConfDir}/hosts") ) {
+ return "Can't open $s->{ConfDir}/hosts";
+ }
+ foreach my $host ( keys(%$hosts) ) {
+ my $name = "$hosts->{$host}{host}";
+ my $rest = "\t$hosts->{$host}{dhcp}"
+ . "\t$hosts->{$host}{user}"
+ . "\t$hosts->{$host}{moreUsers}";
+ $name =~ s/ /\\ /g;
+ $rest =~ s/ //g;
+ $hostText->{$host} = $name . $rest;
+ }
+ binmode(HOST_INFO);
+ while ( <HOST_INFO> ) {
+ s/[\n\r]+//;
+ if ( /^\s*$/ || /^\s*#/ ) {
+ $contents .= $_ . "\n";
+ next;
+ }
+ if ( !$gotHdr ) {
+ $contents .= $_ . "\n";
+ $gotHdr = 1;
+ next;
+ }
+ @fld = split(/(?<!\\)\s+/, $1);
+ #
+ # Remove any \
+ #
+ foreach ( @fld ) {
+ s{\\(\s)}{$1}g;
+ }
+ if ( defined($hostText->{$fld[0]}) ) {
+ $contents .= $hostText->{$fld[0]} . "\n";
+ delete($hostText->{$fld[0]});
+ }
+ }
+ foreach my $host ( sort(keys(%$hostText)) ) {
+ $contents .= $hostText->{$host} . "\n";
+ delete($hostText->{$host});
+ }
+ close(HOST_INFO);
+
+ #
+ # Write and verify the new host file
+ #
+ return $s->TextFileWrite("$s->{ConfDir}/hosts", $contents);
+}
+