#!/usr/bin/sh
#   Check whether cjdns IPs are available
#   Copyright (C) 2016  Stuart D. Gathman <stuart@gathman.org>
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU 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 General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.

cjdns_ips() {
  ip -6 -o addr | while read i dev fam ip rem; do
    case "$ip" in
    fc*:*/8) echo "${ip%/8}";;
    esac
  done
}

cjdns_dev() {
  ip -6 -o addr | while read i dev fam ip rem; do
    case "$ip" in
    fc*:*/8) echo "${dev}";;
    esac
  done
}

die() {
  echo "$1" >&2
  exit 1
}

PROGRAM_NAME="/usr/bin/cjdns-online"

ARGS=$(getopt -n $PROGRAM_NAME -o t:xiqsh \
	--long timeout:,exit,interface,quiet,wait-for-startup,help -- "$@")

# Die if they fat finger arguments, this program may be run as root
[ $? = 0 ] || die "Error parsing arguments. Try $PROGRAM_NAME --help"

help() {
        cat <<EOH
Usage: $PROGRAM_NAME [options]
        -t, --timeout <timeout_value>	time to wait in seconds, default 30
        -i, --interface 	output interface name instead of ip
        -x, --exit		exit immediately if cjdns is not online
        -q, --quiet		don't print anything
        -s, --wait-for-startup	wait for full startup instead of just tun dev
EOH
        exit 2
}

let timeout="30"
let nowait="0"
let quiet="0"
let startup="0"
let interface="0"

eval set -- "$ARGS"
while true; do
  case "$1" in
    -t|--timeout)	   let timeout="$2" || help; shift 2; continue;;
    -i|--interface)	   let interface="1"; shift;;
    -x|--exit)		   let nowait="1"; shift;;
    -q|--quiet)		   let quiet="1"; shift;;
    -s|--wait-for-startup) let startup="1"; shift;;
    --) shift; break;;
    *)	help;;
  esac
done

let started="$(date +%s)"
while test -z "$(cjdns_ips)"; do
  let elapsed="$(date +%s) - $started"
  [ $elapsed -gt $timeout ] && exit 1
  sleep 2
done
if [ "$quiet" -eq 0 ]; then
  if [ "$interface" -eq 0 ]; then
    cjdns_ips
  else
    cjdns_dev
  fi
fi
