#!/bin/sh
#
# uhome
#
# Copyright 2014 Dustin Kirkland <dustin.kirkland@gmail.com>
#
# Licensed 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.


set -e

PKG="uhome"
[ -n "$SNAPP_APP_USER_DATA_PATH" ] && DATADIR="$SNAPP_APP_USER_DATA_PATH" || DATADIR="$HOME/.$PKG/"
STATE="$DATADIR/state"
mkdir -p $(dirname "$STATE")
FILE="$DATADIR/addresses"
touch "$FILE"
TRIES=10
QUIET=0
while [ ! -z "$1" ]; do
	case "${1}" in
		-f|--file)
			FILE="$2"
			shift 2
		;;
		-q|--quiet)
			QUIET="1"
			shift 1
		;;
		-t|--tries)
			TRIES="$2"
			shift 2
		;;
		*)
			echo "Unknown options [$1]" 1>&2
			exit 1
		;;
	esac
done


is_ip() {
	echo "$1" | grep -qs "^[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}$" >/dev/null 2>&1
}

test_addr() {
	local addr="$1"
	local i=0
	local ip=0
	if is_ip "$addr"; then
		ip="$addr"
	else
		echo "ERROR: Invalid address in configuration file [$addr]" 1>&2
		exit 1
	fi
	ping -q -W 1 -c 1 "$addr" >/dev/null 2>&1 && return
	false
}

set_state() {
	local state="$1"
	case "$state" in
		0)
			[ "$QUIET" = "1" ] || echo "$PKG →  Yep!"
			echo 0 >"$STATE"
			exit 0
		;;
		1)
			[ "$QUIET" = "1" ] || echo "$PKG →  Nope!"
			echo 1 >"$STATE"
			exit 1
		;;
	esac
}

addrs=$(cat "$FILE" | grep -v "^#") || true
if [ -z "$addrs" ]; then
	echo "ERROR: Please add one or more IP addresses to [$FILE]" 2>&1
	exit 1
fi

for i in $(seq 1 $TRIES); do
	for addr in $addrs; do
		test_addr "$addr" && set_state 0 || continue
	done
done
set_state 1
