#!/bin/bash
#
# set-macos-hostname - Set the system hostname on macOS, robust-ish-ly.
#
# sudo set-macos-hostname <name>
#
# Sets the hostname in all the various ways you need to on OS X. This is intended to be
# the equivalent of manually setting it in the System Preferences > Sharing control
# panel.
#
# I'm not sure if this actually works.

# Load JXL. See "Loading JXL" in dots/README.md.
source "$(cd "$(dirname "$0")" && pwd -P)/../dots/all-os/flat/dotlib/jxl-lib.sh" \
    || { echo >&2 "ERROR: failed to load jxl-lib.sh"; exit 1; }

jxl::init_script
jxl::use_short_names

OPT_TRACE=0
HOSTNAME_ARG=

function usage() {
  cat <<EOF
$PROGRAM_NAME - Set the hostname on this macOS machine.

Usage:
  $PROGRAM_NAME [--trace] <hostname>
  $PROGRAM_NAME --help

Options:
    -x, --trace     trace program execution
$(jxl::std_options_help)
EOF
}

function main() {
  if [[ $OPT_TRACE = 1 ]]; then set -o xtrace; fi

  set-macos-hostname "$HOSTNAME_ARG"
}

function parse_cli() {
  local arg
  local -a positionals=()

  while [[ $# -ge 1 ]]; do
    arg="$1"; shift
    case "$arg" in
      --trace | -x)                 OPT_TRACE=1 ;;

      --)                           break ;;
      -*)
        jxl::std_opt "$arg" \
            || die "Unexpected option: ${arg}. See '$PROGRAM_NAME --help' for usage"
        if [[ $_JXL_WANT_HELP == 1 ]]; then usage; exit 0; fi
        ;;
      *)                            positionals+=("$arg") ;;
    esac
  done
  # A hostname after `--` is still a hostname, even if it looks like an option.
  positionals+=("$@")

  # The old getopts loop never shifted past the options, so `$1` was still the first
  # option: `set-macos-hostname -x myhost` quietly set the hostname to "-x".
  if [[ ${#positionals[@]} -ne 1 ]]; then
    die "Expected exactly one <hostname> argument, got ${#positionals[@]}." \
        "See '$PROGRAM_NAME --help' for usage"
  fi
  HOSTNAME_ARG="${positionals[0]}"

  readonly OPT_TRACE HOSTNAME_ARG
}

function set-macos-hostname() {
  local name="$1"
  sudo scutil --set ComputerName "$name"
  sudo scutil --set HostName "$name"
  sudo scutil --set LocalHostName "$name"
  sudo defaults write /Library/Preferences/SystemConfiguration/com.apple.smb.server NetBIOSName -string "$name"
}

parse_cli "$@"
main
exit 0
