#!/bin/sh
################################################################################
#      This file is part of LibreELEC - https://libreelec.tv
#      Copyright (C) 2016 Team LibreELEC
#
#  LibreELEC 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 2 of the License, or
#  (at your option) any later version.
#
#  LibreELEC 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 LibreELEC.  If not, see <http://www.gnu.org/licenses/>.
################################################################################

. /etc/profile
oe_setup_addon service.system.tinc

config="$ADDON_HOME/.config"
dev="vmnetz"
host="$ADDON_HOME/Host"
hosts="$ADDON_HOME/Hosts"

rm -rf "$host"
rm -f "$hosts"

if [ -z "$tinc_name" ]
then
   rm -rf "$config"
   exit 0
fi

read_name="$(tinc -c $config get name)"

if [ "$read_name" != "$tinc_name" ]
then
   rm -rf "$config"
   tinc -c "$config" init "$tinc_name"
fi

mkdir -p "$host"
ln -s "$config/hosts/$tinc_name" "$host/$tinc_name"
ln -nsf "$config/hosts" "$hosts"

for var in address port subnet
do
   eval "tinc_var=\$tinc_$var"
   if [ -z "$tinc_var" ]
   then
      tinc -c "$config" del "$var"
   else
      tinc -c "$config" set "$var" "$tinc_var"
   fi
done

cp "$ADDON_DIR/bin/subnet-up" \
   "$ADDON_DIR/bin/tinc-up"   \
   "$config"

case "$tinc_subnets" in
   "default")
      subnets=""
      ;;
   "strict subnets")
      subnets="-o StrictSubnets=yes"
      ;;
   "tunnel server")
      subnets="-o TunnelServer=yes"
      ;;
esac

tincd -c "$config"          \
      -n "$dev"             \
      -o AutoConnect=yes    \
      -o LocalDiscovery=yes \
      -o mode="$tinc_mode"  \
      $subnets
