#!/bin/bash
#
# XR interception of Linux `hostname` command.
# Reports the XR node name (such as xr-vm_node0_RP0_CPU0) instead of the
# configured hostname, as various XR processes expect this.
#
# September 2016, Glenn F. Matthews
#
# Copyright (c) 2016-2017 by Cisco Systems, Inc.
# All rights reserved.

source /etc/init.d/spirit_log.sh

function get_nodename()
{
    local NODEFILE='/etc/nodename'
    # NODEFILE is populated by processmgr, so we need to fail gracefully
    # if called before processmgr has started.
    if [ ! -f $NODEFILE ]; then
        /bin/hostname
        return
    fi
    cat $NODEFILE
}

function set_nodename()
{
    local NODEFILE='/etc/nodename'
    # Normally NODEFILE is populated by processmgr, not by this script.
    # This is unusual, so log it in a user-visible way...
    if [ -f $NODEFILE ]; then
        platform_log_syslog_warning "Changing nodename from '`cat $NODEFILE`' to '$1'"
    else
        platform_log_syslog_notice "Setting nodename to '$1'"
    fi
    echo "$1" > $NODEFILE
}

if [ "$#" -eq 0 ]; then
    # Expected case - just print the nodename and exit
    get_nodename
else
  # Handle the unexpected cases now:
  found_options="false"

  for param in "$@"; do
    case "$param" in
      -h | --help)
        echo "/pkg/bin/hostname" >&2
        echo "Prints the XR node name such as 'xr-vm_node0_RP0_CPU0'." >&2
        echo "This script should only be called by XR processes." >&2
        echo "Linux processes and users should call /bin/hostname instead." >&2
        # To match /bin/hostname -h exit code:
        exit 4
        ;;
      -*)
        found_options="true"
        ;;
      *)
        if [ -z "$NODENAME" ]; then
          NODENAME="$param"
        fi
        ;;
    esac
  done

  if [ "$found_options" == "true" ]; then
    echo "WARNING: /pkg/bin/hostname shouldn't be called with options!" >&2
    echo "WARNING: Passing options over to /bin/hostname." >&2
    /bin/hostname "$@"
    exit $?
  else
    set_nodename "$NODENAME"
  fi
fi
