#!/bin/sh

# Config file
CONF_FILE="/etc/bosixnet/bosixnet-daemon.conf"

# Directory where generated host file is stored
LOG_DIR="/var/tmp/bosixnet"

# Default web-site URL
URL="http://ipv6.example.com/bosixnet"

# Read settings from config file if it exists
[ -e "${CONF_FILE}" ] && . "${CONF_FILE}"


# Protect file with list of hosts from simultaneous editing
SCRIPT_NAME="$(basename ${0})"
if [ ! -z "$(pidof -o %PPID -x ${SCRIPT_NAME})" ]; then
    echo "Another instance of ${SCRIPT_NAME} script is already running."
    echo "Please wait until it is finished and try again."
    exit 1
fi

HOSTS="/etc/hosts"
FILE="${LOG_DIR}/hosts"

[ -e "${FILE}" ] && CUR_INFO="$(cat ${FILE} | grep '^....:.*:.*:.*')"

if [ -z "${CUR_INFO}" ]; then
    echo "File ${FILE} does not exist or does not contain correct data."
    for DEST in ${URL} ; do
        LINK="${DEST}/hosts"
        echo "Trying to get data from ${LINK}..."
        CUR_INFO="$(curl -L ${LINK} 2>/dev/null | sed 's/<br>//' | grep '^....:.*:.*:.*')"
        if [ -z "${CUR_INFO}" ]; then
            echo "Attempt to get data from ${LINK} failed."
        else
            echo "Data from ${LINK} have been received successfully."
            break
        fi
    done
fi

if [ -z "${CUR_INFO}" ]; then
    echo "Data failed to be received from specified resources."
    exit 1
fi

cp -f "${HOSTS}" "${HOSTS}.backup"
cat "${HOSTS}.backup" | grep -v '^....:.*:.*:.*' | tee "${HOSTS}" > /dev/null
echo "${CUR_INFO}" | tee -a "${HOSTS}" > /dev/null

