#!/bin/bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
# 
#   http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

# $1: string
# print 1 for success, 0 for fail
function is_ipv4() 
{
    if [[ $1 =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
        echo "1"
    else
        echo "0"
    fi
}

# $1: an ip_addr
function is_site_local_addr()
{
    # 10.*.*.*
    if [[ $1 =~ ^10\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
        echo "1"
    # 172.16.*.*
    elif [[ $1 =~ ^172\.16\.[0-9]+\.[0-9]+$ ]]; then
        echo "1"
    # 192.168.*.*
    elif [[ $1 =~ ^192\.168\.[0-9]+\.[0-9]+$ ]]; then
        echo "1"
    else
        echo "0"
    fi
}

got_result="0"
for ip in `hostname -I`; do 
    if [ "1" == `is_site_local_addr $ip` ]; then
        echo $ip
        got_result="1"
        break
    fi
done

if [ "0" == $got_result ]; then
    echo "127.0.0.1"
fi
