#!/bin/sh /etc/rc.common
# Copyright (C) 2007 OpenWrt.org

START=99

list_servers() {
  SERVER_PARAMS=" -SER[Shost:"
	config_get host "$1" 'host'
	config_get port "$1" 'port'
	config_get atoken "$1" 'atoken'
	SERVER_PARAMS="${SERVER_PARAMS}""${host}"",Sport:""${port}"
  [ ! $atoken ] && SERVER_PARAMS=${SERVER_PARAMS}"]" || SERVER_PARAMS=${SERVER_PARAMS}",Atoken:${atoken}]"
  eval ${1}_PARAMS=\$SERVER_PARAMS
}

list_tunnels() {
  config_get_bool enabled "$1" 'enabled'
  config_get type "$1" 'type'
	config_get lhost "$1" 'lhost'
	config_get server "$1" 'server'
	config_get lport "$1" 'lport'
	config_get custom_domain "$1" 'custom_domain'
	config_get rport "$1" 'rport'
	config_get dname "$1" 'dname'
	[ -z "$lhost" ] && lhost="127.0.0.1"
  if [ "$enabled" = 1 ]; then
    TUNNEL_PARAMS=" -AddTun[Type:${type},Lhost:${lhost},Lport:${lport}"
    [ "z"$custom_domain = "z1" ] && DTYPE="Hostname" || DTYPE="Sdname"
    [ ${type} = "tcp" ] && \
	TUNNEL_PARAMS=${TUNNEL_PARAMS}",Rport:${rport}]" || \
	TUNNEL_PARAMS=${TUNNEL_PARAMS}",${DTYPE}:${dname}]"
    echo $server" : ngrokc"$TUNNEL_PARAMS
    config_foreach list_servers 'servers'
    eval "exec /usr/bin/ngrokc \$${server}_PARAMS \$TUNNEL_PARAMS 2>&1 > /dev/null & echo \$! >> /tmp/ngrokc/${1}.pid"
  fi
}

start() {
	mkdir -p /tmp/ngrokc
	config_load 'ngrokc'
	 [ -f /tmp/ngrokc/ngrokc_running ] || \
	 ( config_foreach list_tunnels 'tunnel' ; touch /tmp/ngrokc/ngrokc_running )
}

stop() {
	kill -2 `pidof ngrokc|sed "s/$$//g"` 2>/dev/null
	rm -f /tmp/ngrokc/*
	sleep 2
}

boot() {
	sleep 10
	start
}
