#!/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
}

runnrokc() {
	eval "exec /usr/bin/ngrokc \$${1}_PARAMS \$${1}_TUNNEL_PARAMS 2>&1 > /dev/null & echo \$! >> /tmp/ngrokc/${1}.pid"
}



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
    eval TUNNEL_PARAMS=\$${server}_TUNNEL_PARAMS
	TUNNEL_PARAMS=$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 ${server}_TUNNEL_PARAMS=\$TUNNEL_PARAMS
  fi
}



start() {
	mkdir -p /tmp/ngrokc
	config_load 'ngrokc'
	 [ -f /tmp/ngrokc/ngrokc_running ] || \
	 ( config_foreach list_tunnels 'tunnel' ; config_foreach runnrokc 'servers'; 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
}
