#! /bin/sh

HOSTS="$CONFDIR/hosts"

hosts_loaded=

printhost()
{
  echo "Host read:"
  echo "  Host: $HOST"
  echo "  Hostprefix: $HOSTPREFIX"
  echo "  Target: $TARGETS"
  [ -z "$SUBHOST" ] || echo "  Subhost: $SUBHOST"
}

resetHosts()
{
  hosts_loaded=
  if ! [ -f "$HOSTS" ]; then
    logprint "Hosts file does not exist"
    return 1
  fi
}

getHost()
{
  if [ "$hosts_loaded" = "" ]; then
    if ! exec 3<$HOSTS; then
      return 1
    fi
    hosts_loaded=1
    echo "$HOSTS loaded"
  fi

  export HOST=
  export HOSTPREFIX=
  export TARGETS=
  export SUBHOST=

  while <&3 read -r REPLY; do
    REPLY=${REPLY##\#*}
    if [ -z "$REPLY" ]; then
      if ! [ -z "$TARGETS" ]; then
        printhost
        return 0
      fi
      continue;
    fi

    if [ -z "$HOST" ]; then
      export HOST="$REPLY"
    elif [ -z "$HOSTPREFIX" ]; then
      export HOSTPREFIX="$REPLY"
    elif [ -z "$TARGETS" ]; then
      export TARGETS="$REPLY"
    elif [ -z "$SUBHOST" ]; then
      export SUBHOST="$REPLY"

      printhost
      return 0
    fi
  done

  if [ -z $TARGETS ] && ! [ -z $HOST ]; then
    echo "Premature end of hosts file"
    return 1
  fi

  if ! [ -z "$TARGETS" ]; then
    printhost
    return 0
  fi

  return 1
}
