#!/bin/bash
#
# .---.                  .              .
# |                      |              |
# |--- .--. .-.  .-.  .-.|  .-. .--.--. |.-.  .-. .--.  .-.
# |    |   (.-' (.-' (   | (   )|  |  | |   )(   )|  | (.-'
# '    '     --'  --'  -' -  -' '  '   -' -'   -' '   -  --'
#
#                    Freedom in the Cloud
#
# Web interface for the mesh
#
# License
# =======
#
# Copyright (C) 2015-2016 Bob Mottram <bob@robotics.uk.to>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

PROJECT_NAME='freedombone'

export TEXTDOMAIN=${PROJECT_NAME}-meshweb
export TEXTDOMAINDIR="/usr/share/locale"

MESH_INSTALL_DIR=/var/lib
PEERS_FILE=/tmp/meshwebstart

if [ -d $MESH_INSTALL_DIR/zeronet ]; then
    ZERONET_DIR=$MESH_INSTALL_DIR/zeronet
fi

avahi-browse -atl | awk -F ' ' '{print $4}' | sort -u > $PEERS_FILE

if [ ! -f $PEERS_FILE ]; then
   echo $'No peers were found'
   exit 0
fi

# count the peers
ctr=0
while IFS='' read -r line || [[ -n "$line" ]]; do
    ctr=$((ctr + 1))
done < "$PEERS_FILE"
rm $PEERS_FILE

# enough peers
if [ ${ctr} -lt "1" ]; then
   echo $'No peers were found'
   exit 0
fi

ZERONET_INDEX=$MESH_INSTALL_DIR/zeronet/mesh.html

if which firefox > /dev/null; then
    firefox $ZERONET_INDEX
elif which midori > /dev/null; then
    midori $ZERONET_INDEX
elif which iceweasel > /dev/null; then
    iceweasel $ZERONET_INDEX
elif which chrome > /dev/null; then
    chrome $ZERONET_INDEX
elif which chromium > /dev/null; then
    chromium $ZERONET_INDEX
elif which xdg-open > /dev/null; then
    xdg-open $ZERONET_INDEX
elif which gnome-open > /dev/null; then
    gnome-open $ZERONET_INDEX
fi

exit 0
