#!/bin/sh

. /lib/functions.sh
. /lib/netifd/netifd-proto.sh
. /usr/share/libubox/jshn.sh
case "$1" in
	list)
 		 echo '{ "set_timezone" : {"tz" : "CET-1CEST,M3.5.0,M10.5.0/3"},
			"set_language" : {"language" : "en"},
			"update" : {"auto":"false", "url":"http://example"}, 
                        "client" : {"code" : "6s58s54444"},
                        "plugandcharge" : {},
                        "enable" : {"service" : "ocppdv16" },
                        "disable" : {"service" : "rfidd" },
			"discover_services" : {"service":"service"} ,
			"active_service":{"service":"service"}, 
			"reboot":{}, 
			"reboot_04M":{"conn":"conn"}, 
			"upgrade_software" : {}, 
			"distribute_update_package" : {} , 
                        "smartcharging" : { "max_current_plant" : 0,
                                            "max_current_chargingpoint" : 32,
                                            "phases_chargingpoint" : "rst",
                                            "logical_connector" : "chademoccs",
                                            "max_current_logical_connector" : 80,
                                            "phases_logical_connector" : "rst",
                                            "logical_connector" : "mennekesleft",
                                            "max_current_logical_connector" : 32,
                                            "phases_logical_connector" : "rst",
                                           },
			"network" : {"proto":"dhcp", "options" : {}},
			"modbusserver" : {"interface":"192.168.2.2" },
               "wifi" : {"mode" : "ap|station|mesh", "options" : {}},
			"restart_network" : {}, 
			"check_internet_connection" : {}, 
			"check_file_existence" : {"path":"path"}, 
			"compress_dir" : {"path":"path"}, 
			"restore_backup" : {"path":"path"} , 
			"get_remote_file" : {"ip":"ip", "name":"name"},
			"copy_file" : {"src_path":"src_path", "dst_path":"dst_path", "delete_from_src":true}, 
			"logread_remote" : {}, 
			"update_firmware" : {}, 
			"delete_file" : {"path":"path"},
			"configure_update_period" : {"period":1},
			"tests": {"test":"test"}, 
			"generate_hash": {"string":"string", "path":"path"}, 
			"is_display_video_available" : {"url":"url"},
			"download_display_video":{"url": "url"}, 
			"recipes_to_file" : {},
			"bpm_info" : {"canid":"canid", "dst_path":"path"},
			"execute_script" : {},
			"sysupgrade":{"sn":"sn"},
			"create_dir":{"path":"path"},
			"transferfiles_bg":{"path":"path", "sn":"sn","dst_path":"dst_path" }, 
         
	}'
	;;
	call)
		case "$2" in
	  		set_timezone)
                       	 read input;
                       	json init
                       	json_load "$input"

                  					
			json_get_var timezone timezone
			 json_get_var zonename zonename

			 ubus call uci set '{"config":"system", "type":"system", "values":{"timezone":"'$timezone'", "zonename":"'$zonename'"}}'
			 ubus call uci commit '{"config":"system"}'
                         /etc/init.d/system restart
			 #logger -t "set_configuration" "$k" "is: " "$v"
  			 echo '{"timezone":"'$timezone'", "zonename" : "'$zonename'"}'
			
			;;
			set_language)
                       	 read input;
                       	json init
                       	json_load "$input"
                         json_get_keys keys
			for k in $keys; do 
  				 json_get_var v "$k"
				 ubus call uci set '{"config":"luci", "section":"main", "values":{"lang":"'$v'"}}'
			         ubus call uci commit '{"config":"luci"}'
				obj=$(ubus list h* | grep hmi | grep -v "\/")
				if [ -z "$obj" ]
				then
					result=$(ubus list  6* | grep -v "\." | grep -v "\/")
					for z in $result; do 
						ubus call $z set_configuration '{"hmi":{"language":"'$v'"}}'  
						break

					done

				else
					ubus call hmi set_configuration '{"language":"'$v'"}'

				fi
				 #logger -t "set_configuration" "$k" "is: " "$v"
  				 echo '{"'$k'":"'$v'"}'
			done
			;;
		
			update) 
			 read input;
                       	json init
                       	json_load "$input"
                         json_get_keys keys
			for k in $keys; do 
  				 json_get_var v "$k"
				json_get_var auto auto
				json_get_var url url
				
				if [ ! -z url ]
				then
					ubus call swupdated set_configuration '{"auto" : '$auto', "url":"'$url'"}'

				else

					ubus call swupdated set_configuration '{"auto" : '$auto'}'

				fi
  				 #echo '{"auto":'$auto'", "url":"'$url'"}'


			done

			;; 
 			client)
			read input;
                       	json init
                       	json_load "$input"
                         json_get_keys keys
			for k in $keys; do 
  				 json_get_var v "$k"
				 case "$v" in
                       			 6962657264726f6c61)
					/usr/bin/iberdrola.sh
					echo '{"code":"6962657264726f6c61"}'
		                    	 ;;
                       			 6962696c)
                       			 /usr/bin/ibil.sh
					echo '{"code":"6962696c"}'

                       			 ;;
                       			 66656e6965)
                       			 /usr/bin/fenie.sh
					echo '{"code":"66656e6965"}'

                       			 ;;
                       			 626f736368)
                       			 /usr/bin/bosch.sh
					echo '{"code":"626f736368"}'

                       			 ;;
                       			 656c656374726f6d617073)
                       			 /usr/bin/etecnic.sh
					echo '{"code":"656c656374726f6d617073"}'

                       			 ;;
                       		 esac
				
					
			done
			;;

			plugandcharge)
                         #stop services
                        /etc/init.d/rfidd stop
                        /etc/init.d/rfidd disable
                        /etc/init.d/ocppdv15 stop
                        /etc/init.d/ocppdv15 disable
                        /etc/init.d/ocppdv16 stop
                        /etc/init.d/ocppdv16 disable
                         change settings
                         disable remote auth for all logical connectors
                        lcs=$(ubus list 6* | grep '\.')
                        for lc in $lcs
                        do
                            ubus call $lc set_configuration '{"remote_auth":false}'
                        done
                         #restart services
			/etc/init.d/accontroller restart
                        /etc/init.d/hmi restart
                    ;;
			 enable)
                        read input;
                       	json init
                       	json_load "$input"
                        json_get_keys keys
                         #json_get_var v "$k"
			for k in $keys; do 
  				 json_get_var v "$k"
				logger "wizard enable" "$v"

				if [ "$v" = "ocppdv15" ] || [ "$v" = "ocppdv16" ]	
				then

				
				 json_get_var backend_url backend_url
				 if [ ! -z "$backend_url" ]
				 then
					ubus call uci set '{"config":"ocppd", "section":"internal", "values":{"backend_url":"'$backend_url'"}}'
				 fi
				
				 /etc/init.d/ocppdv15 stop
				 /etc/init.d/ocppdv15 disable
                          	 /etc/init.d/ocppdv16 stop
				 /etc/init.d/ocppdv16 disable
				 /etc/init.d/$v enable
                          	 /etc/init.d/$v restart
				 /etc/init.d/localbackend stop 
				 /etc/init.d/localbackend disable
				 sleep 5
				 /etc/init.d/owsd restart
				result=$(echo "$backend_url" | grep  "ws")
				if [ ! -z "$result" ]
				then
					 result=$(ubus list 6* | grep /wizard )

					 for z in $result; do 
				 		#logger -t "JSON" "backend_url" "is: " "$backend_url"
							
						ubus call $result enable '{"service":"'$v'", "backend_url":"'$backend_url'"}' & 


					done 

				fi

				elif [ "$v" = "extpwrmeterd" ]
				then
					/etc/init.d/$v enable
					/etc/init.d/$v restart
					/etc/init.d/mbusd stop 
					/etc/init.d/mbusd disable 
					/etc/init.d/modbuspoller stop 
					/etc/init.d/modbuspoller disable
					rtu=$(uci get modbusserver.internal.interface | grep "/dev")
					if [ ! -z "$rtu" ]
					then 
						logger "disable modbusserver"
						/etc/init.d/modbusserver stop
						/etc/init.d/modbusserver disable
					fi

				elif [ "$v" = "modbuspoller" ]
				then 
					/etc/init.d/modbuspoller enable
					/etc/init.d/modbuspoller restart
					/etc/init.d/mbusd enable
					/etc/init.d/mbusd restart
					/etc/init.d/extpwrmeterd stop
					/etc/init.d/extpwrmeterd disable
					/etc/init.d/modbusserver stop
					/etc/init.d/modbusserver disable


				elif [ "$v" = "modbusserver" ]
				then 
					/etc/init.d/modbusserver enable
					/etc/init.d/modbusserver restart 
					/etc/init.d/mbusd stop 
					/etc/init.d/mbusd disable
					/etc/init.d/modbuspoller stop 
					/etc/init.d/modbuspoller disable

					
					
				elif [ "$k" = "modbus_id" ]
				then
					uci set extpwrmeterd.powermeter.modbus_id=$v
					uci commit extpwrmeterd

				elif [ "$v" = "rfidd" ]
				then
					/usr/bin/enable_rfid.sh 1 
 					result=$(ubus list 6* | grep /wizard )
					 for z in $result; do
 						ubus call $z enable '{"service":"'$v'"}' 
					done 

				elif [ "$v" = "rtty" ]
				then
					/etc/init.d/rtty enable 
					/etc/init.d/rtty restart 
					uci set healthcheck.internet_connection.force_disable_rtty='off'
					uci commit healthcheck

				elif [ "$v" = "localbackend" ]; then
					/etc/init.d/localbackend enable
					/etc/init.d/localbackend restart 
					/etc/init.d/ocppdv16 stop 
					/etc/init.d/ocppdv16 disable
					/etc/init.d/ocppdv15 stop 
					/etc/init.d/ocppdv15 disable
				else
 				/etc/init.d/$v enable
                          	 /etc/init.d/$v restart
				fi 

				echo '{"'$k'":"'$v'"}'
			done
                         			  
                    ;;
			 disable)
                         read input;
                       	json init
                       	json_load "$input"
                         json_get_keys keys
                         #json_get_var v "$k"
			for k in $keys; do 
				 #logger -t "disable" "$k" "is: " "$v"
  				 json_get_var v "$k"
				logger "wizard disable" "$v"
				 /etc/init.d/$v disable
                          	 /etc/init.d/$v stop  	
				if [ "$v" = "ocppdv15" ] || [ "$v" = "ocppdv16" ]	
				then
					system=$(ubus call system board)
					json_load "$system"
					json_get_var hostname hostname
					 ##logger -t "hostname" "$hostname" 
					/etc/init.d/owsd restart

						if [ ! -z "$hostname" ]
						then 
							ubus call $hostname set_configuration '{"remote_auth" : false}'
						fi

				elif [ "$v" = "rfidd" ]
				then				

					/usr/bin/enable_rfid.sh 0  
 					result=$(ubus list 6* | grep /wizard )
					if [ ! -z "$result" ]
					then
					 for z in $result; do 
						ubus call $z disable '{"service":"'$v'"}' & 

					done
					fi 


				elif [ "$v" = "rtty" ]
				then
					/etc/init.d/rtty disable 
					/etc/init.d/rtty stop 
					uci set healthcheck.internet_connection.force_disable_rtty='on'
					uci commit healthcheck
				elif [ "$v" = "ingeruled" ]; then
					/etc/init.d/ingeruled disable
					/etc/init.d/InotifydConfig disable
					/etc/init.d/ingeruled stop
					/etc/init.d/InotifydConfig stop 



				fi

				 echo '{"'$k'":"'$v'"}'
			done
                        
                    ;;

			discover_services)
                       	read input;
                       	json init
                       	json_load "$input"
                        json_get_var service service
			if [ ! -z "$service" ] 
			then 
				 path="/etc/init.d/$service"

				 if [ -e "$path" ]
				 then 

					echo '{"found":"true"}'					
				 fi
				echo '{"found":"false"}'
			else
				json_init
				json_add_array alist
				for file in /etc/init.d/*; do
					str="$(basename "$file")"
					json_add_string "" "$str"
					
					
				done
				json_close_array				
				json_close_object
				msg=$(json_dump)
				echo $msg
					
					
			fi
  			
			;;
			active_service)
				read input;
                       		json init
                       		json_load "$input"
                        	json_get_var service service
				if [ ! -z "$service" ] 
				then 
					res=$(ls /etc/rc.d/ | grep $service )
					if [ ! -z "$res" ]
					then

						echo '{"enabled":"true"}'
					fi
						echo '{"enabled":"false"}'

				fi
			
			;;
			reboot) 
			
	
				reboot
			;;
			reboot_04M)
				read input;
                       		json init
                       		json_load "$input"
                        	json_get_var conn conn
				ubus call $conn set_fsm '{"fsm":"reset"}'
			;;
			upgrade_software)
				logger -t "upgrade_software"
				opkg update  >/tmp/update_out 2>&1
				ret=$(cat /tmp/update_out | grep Failed)
				if [[ ! -z "$ret"  ]];then 
					echo '{"upgradable":"Could not update package list"}'
				fi
				upgradable_before=$(opkg list_upgradable)
				ret=$(opkg upgrade)
				
				upgradable_after=$(opkg list_upgradable)

				if [[ -z "$upgradable_after" ]];then
					logger "upgrade_software success "
					echo '{"success":"Update correct"}'
				else
					logger "upgrade_software fail "

					json_init
					json_add_array upgradable
					opkg list_upgradable > /tmp/upgradable.txt
					while read line; do
						json_add_string "" "$line"
					done < /tmp/upgradable.txt				
					json_close_array
					rm /tmp/upgradable.txt			
					out=$(json_dump)
					echo $out
				fi

			;; 

			distribute_update_package)
				 result=$(ubus list 6* | grep /wizard )
				 if [ ! -z "$result" ]
				 then
					role=$(uci get owsd.global.role)
					#logger -t "role" "$role" 
					if [ "$role" = "master" ]
					then
						cd /tmp 
						tar -czf update.tar.gz *.opk
						cp update.tar.gz /www
						chmod a=r  /www/update.tar.gz
						ipaddr=$(uci get network.lan.ipaddr)
								

						for i in $(echo $(uci get -d "," uhttpd.main.listen_http ) | tr "," "\n" | tr ":" "\n")
						do
								if [ -n "$i" ] && [ "$i" -eq "$i" ] 2>/dev/null; then
									port=$i
									break; 
								fi
						done
						
						#logger -t "ipaddr" "$ipaddr" "port" "$port" 
						for z in $result
						do
							ubus call $z distribute_update_package '{"ipaddr":"'$ipaddr'", "port":"'$port'"}' 

						done
						echo '{"done":"true"}'

						
					fi

				else 
 					read input;
                         		json_init
                          		json_load "$input"
                        		json_get_keys keys
					json_get_var ipaddr ipaddr
					json_get_var port port 
					if [ ! -z "$ipaddr"  ] && [ ! -z "$port" ] 
					then
					#logger -t "ipaddr" "$ipaddr" "port" "$port" 
						#logger -t "wget ipaddr" http://"$ipaddr":"$port"/update.tar.gz
						cd /tmp
						wget http://"$ipaddr":"$port"/update.tar.gz
						tar xvzf update.tar.gz
  					
												
					fi
					
				fi 			
					
			;;
      			 smartcharging)
                          read input;
                          json_init
                          json_load "$input"
                          json_get_keys keys
			  result=$(ubus list 6*)
			  system=$(ubus call system board)
				json_load "$system"
				json_get_var hostname hostname
				if [ ! -z "$hostname" ]
				then 
					sn=$hostname	
				fi

                         json_load "$input"
                         json_get_keys keys

                        for k in $keys; do
                            json_get_var v "$k"
                            case "$k" in
                                "max_plant_current")
				#logger -t "smartchargingd" "$k" "is: " "$v"
					ubus call smartchargingd set_configuration '{"plant": {"max_current":'$v'}}'
					echo '{"max_plant_current": "'$v'"}'
                                ;;
                                "max_current_chargingpoint")
					ubus call smartchargingd set_configuration '{"'$sn'":{"max_current":'$v'}}'
				echo '{"max_current_chargingpointd": '$v'}'

                                ;;
                                "phases_chargingpoint")
					ubus call smartchargingd set_configuration '{"'$sn'":{"rst":"'$v'"}}'
				echo '{"phases_chargingpoint": '$v'}'

                                ;;
                           
                                esac
                        done
                    ;;

			network)
			   read input;
                       	   json init
                       	   json_load "$input"
                           json_get_keys keys
			   proto=""
			   options=""
			   for k in $keys; do 
  				 json_get_var v "$k"
				 #logger -t "network" "$k" "is: " "$v"

				 if [ "$k" = "proto" ] && [ "$v" = "static" ]
				 then 
					json_select options
					json_get_var ip ipaddr
					uci set network.lan.proto=$v
					if [ ! -z "$ip" ] 
					then
						#logger -t "network" "IP" "is: " "$ip"

                               			uci set network.lan.ipaddr=$ip	
					fi
					json_get_var mask netmask
					if [ ! -z "$mask" ] 
					then
						#logger -t "network" "mask " "is: " "$mask"

						uci set network.lan.netmask=$mask
					fi

					json_get_var gate gateway 
					if [ ! -z "$gate" ] 
					then
						#logger -t "network" "gate" "is: " "$gate"

						uci set network.lan.gateway=$gate
					fi

					json_get_var dns dns
					if [ ! -z "$dns" ] 
					then
						#logger -t "network" "dns" "is: " "$dns"

						uci set network.lan.dns=$dns
					fi

					uci commit network
					#/etc/init.d/network restart


				 elif [ "$k" = "proto" ] && [ "$v" = "dhcp" ]
				 then

					
					uci set network.lan.proto=$v
					uci commit network
					#/etc/init.d/network restart

				elif [ "$k" = "proto" ] && [ "$v" = "3g" ]
				then
					json_select options 
					json_get_var auto auto 
					 #logger -t "3g" "auto" "is: " "$auto"

					if [ "$auto" = "true" ]
					then


						uci set network.wan.discover_apn=1
						uci set network.wan.username='' 
						uci set network.wan.password=''
						uci set network.wan.apn=''


					else
						 #logger -t "auto" "$k" "is: " "$v"

						uci set network.wan.discover_apn=0
						json_get_var user username 
						uci set network.wan.username=$user
						json_get_var pass password
						uci set network.wan.password=$pass 
						json_get_var apn apn 
						uci set network.wan.apn=$apn
						#logger -t "apn" "$apn" 
						json_get_var auth_pap auth_pap 
						if [[ "$auth_pap" = "true" ]]; then 
							uci set network.wan.pppd_options="refuse-chap"
						elif [[ "$auth_pap" == "false" ]]; then 
							uci delete network.wan.pppd_options
						fi
					fi 
					uci commit network
					#/etc/init.d/network restart

				fi 	

			done
		
			#uci commit network
			#/etc/init.d/network restart

		    ;;


			modbusserver)
                        read input;
                       	   json init
                       	   json_load "$input"
                           json_get_keys keys
			   for k in $keys; do 
  				json_get_var v "$k"
				 #logger -t "modbusserver" "$k" "is: " "$v"

				if [ "$k" = "interface" ]
				then

				system=$(ubus call system board)
				json_load "$system"
				json_get_var hostname hostname

				if [ ! -z "$hostname" ]
				then 

					sn=$hostname
					/etc/init.d/modbus_server start
					ubus call $sn set_configuration '{"modbusserver":{"'$k'":"'$v'"}}'
					echo '{"modbusserver":"prueba"}'
				fi


				fi


			   done

                    ;;

			wifi)
				
			   read input;
                       	   json init
                       	   json_load "$input"
                           json_get_keys keys
			   key_ap="$(uci get wireless.ap.key)"
				#logger "HE ENTRADO A WIZARD WIFI "
			   for k in $keys; do 
  				 json_get_var v "$k"
				if [ "$k" = "mode" ] && [ "$v" = "mesh" ]
				then
					#logger "he entrado ""mesh"
					json_select options
					json_get_var ip ip 
					json_get_var netmask netmask 
					json_get_var gateway gateway

					ssid=$(uci get wireless.sta.ssid)
					key_sta=$(uci get wireless.sta.key)
					encryption=$(uci get wireless.sta.encryption)

					#logger "ip" "$ip" " netmask" "$netmask"
				#############Network#################
				
					#uci delete interfaces
					uci delete network.radio0sta
					uci delete network.radio0ap
					uci delete network.radio0
					uci delete network.radio
					uci delete network.bat0
					uci delete network.bat0_hardif
					uci delete network.bat0_lan
					
					#Add interfaces
					uci set network.bat0="interface"
					uci set network.bat0.proto="batadv"
					uci set network.bat0.routing_algo="BATMAN_IV"
					uci set network.bat0.aggregated_ogms=1
					uci set network.bat0.ap_isolation=0
					uci set network.bat0.bonding=0
					uci set network.bat0.fragmentation=1
					uci set network.bat0.gw_mode="off"
					uci set network.bat0.gw_bandwidth="10000/2000"
					uci set network.bat0.gw_sel_class=20
					uci set network.bat0.log_level=0
					uci set network.bat0.orig_interval=1000
					uci set network.bat0.bridge_loop_avoidance=1
					uci set network.bat0.distributed_arp_table=1	
					uci set network.bat0.multicast_mode=1				
					uci set network.bat0.multicast_fanout=16
					uci set network.bat0.network_coding=0
					uci set network.bat0.hop_penalty=30
					uci set network.bat0.isolation_mark="0x00000000/0x00000000"
	
					uci set network.bat0_hardif="interface"
					uci set network.bat0_hardif.proto="batadv_hardif"
					uci set network.bat0_hardif.master="bat0"
					uci set network.bat0_hardif.mtu=1536
		
					uci set network.bat0_lan="interface"
					uci set network.bat0_lan.ifname="bat0"
					uci set network.bat0_lan.proto="static"
					uci set network.bat0_lan.ipaddr="$ip"
					uci set network.bat0_lan.netmask="$netmask"
					uci set network.bat0_lan.gateway="$gateway"
					uci set network.bat0_lan.ip6assign="60"
		
					uci commit network

				############Wireless###################
					
					#Delete interfaces
					uci delete wireless.radio0
					uci delete wireless.ap
					uci delete wireless.sta
					uci delete wireless.mesh
			
					#Add interfaces
					uci set wireless.radio0="wifi-device"
					uci set wireless.radio0.type="mac80211"
					uci set wireless.radio0.channel=1
					uci set wireless.radio0.phy="phy0"
					uci set wireless.radio0.disabled=0
				
					uci set wireless.ap="wifi-iface"
					uci set wireless.ap.device="radio0"
					uci set wireless.ap.mode="ap"
					uci set wireless.ap.network="radio"
					uci set wireless.ap.encryption="psk2"
					uci set wireless.ap.disabled=1
					uci set wireless.ap.ssid="$(hostname)"
					uci set wireless.ap.key="$key_ap"
			
					uci set wireless.sta="wifi-iface"
					uci set wireless.sta.device="radio0sta"
					uci set wireless.sta.mode="sta"
					uci set wireless.sta.encryption="$encryption"
					uci set wireless.sta.disabled=1
					uci set wireless.sta.ssid="$ssid"
					uci set wireless.sta.key="$key_sta"
					uci set wireless.sta.network="radio0sta"

					
					uci set wireless.mesh="wifi-iface"
					uci set wireless.mesh.device="radio0"
					uci set wireless.mesh.mode="adhoc"
					uci set wireless.mesh.network="bat0_hardif"
					uci set wireless.mesh.ssid="ingerev"
					uci set wireless.mesh.disabled="0"
					
					uci commit wireless

				

	
				elif [ "$k" = "mode" ]
				then 
					#logger "he entrado ""aqui "
					if [ "$v" = "ap" ]
					then 
					#logger "he entrado " "ap"
						
						ssid=$(uci get wireless.sta.ssid)
						key_sta=$(uci get wireless.sta.key)
						encryption=$(uci get wireless.sta.encryption)
				       ########Network config############
						uci delete network.radio0ap
						uci delete network.radio0sta
						uci deletee network.radio
						uci delete.network.radio0
						uci delete network.bat0
						uci delete network.bat0_hardif
						uci delete network.bat0_lan
							
						uci set network.radio0ap="interface"
						uci set network.radio0ap.ifname="wlan0"
						uci set network.radio0ap.proto="static"
						uci set network.radio0ap.ipaddr="192.168.2.1"
						uci set network.radio0ap.netmask="255.255.255.0"
						uci set network.radio0ap.ipv6=1
		
						uci set network.radio0sta="interface"
						uci set network.radio0sta.ifname="wlan1"
						uci set network.radio0sta.proto="dhcp"
						uci set network.radio0sta.ipv6=1
						
						uci commit network

				    	########Wireless config#############
						uci delete wireless.radio0
						uci delete wireless.ap
						uci delete wireless.sta
						uci delete wireless.mesh
	
						uci set wireless.radio0="wifi-device"
						uci set wireless.radio0.type="mac80211"
						uci set wireless.radio0.channel=1
						uci set wireless.radio0.phy="phy0"
						uci set wireless.radio0.disabled=0

						uci set wireless.ap="wifi-iface"
						uci set wireless.ap.device="radio0"
						uci set wireless.ap.mode="ap"
						uci set wireless.ap.network="radio0ap"
						uci set wireless.ap.encryption="psk2"
						uci set wireless.ap.disabled=0
						uci set wireless.ap.ssid="$(hostname)"
						uci set wireless.ap.key="$key_ap"

						uci set wireless.sta="wifi-iface"
						uci set wireless.sta.device="radio0"
						uci set wireless.sta.mode="sta"
						uci set wireless.sta.network="radio0sta"
						uci set wireless.sta.ssid="$ssid"
						uci set wireless.sta.encryption="$encryption"
						uci set wireless.sta.key="$key_sta"
						uci set wireless.sta.disabled=1
		
						uci set wireless.mesh="wifi-iface"
						uci set wireless.mesh.device="radio0"
						uci set wireless.mesh.mode="mesh"
						uci set wireless.mesh.network="radio0"
						uci set wireless.mesh.mesh_id="ingerev"
						uci set wireless.mesh.encryption="psk2"	
						uci set wireless.mesh.key="meshmesh"						
						uci set wireless.mesh.device="radio0"
						uci set wireless.mesh.disabled=1
				
						uci commit wireless
						
				    	########DHCP config#############

						uci set dhcp.radio0ap="dhcp"
						uci set dhcp.radio0ap.interface="radio0ap"
						uci set dhcp.radio0ap.ifname="wlan0"
						uci set dhcp.radio0ap.dhcpv4="server"
						uci set dhcp.radio0ap.start="100"
						uci set dhcp.radio0ap.limit="150"
						uci set dhcp.radio0ap.leasetime="12h"	
			
						uci commit dhcp 
					fi
						
					if [ "$v" = "station" ]
					then 
						#logger "he entrado " "station "
						json_select options
						json_get_var key  key
						json_get_var encryption encryption
						json_get_var ssid ssid 

					###############Network#####################	

						#delete mesh interfaces 
						uci delete network.bat0
						uci delete network.bat0_hardif_mesh0
						uci delete network.bat0_lan 
					
						#delete ap and sta interfaces 
						uci delete network.radio0ap
						uci delete network.radio0sta
						uci delete network.radio
						uci delete wireless.radio0


						uci set network.radio0ap="interface"
						uci set network.radio0ap.ifname="wlan1"
						uci set network.radio0ap.proto="static"
						uci set network.radio0ap.ipaddr="192.168.2.1"
						uci set network.radio0ap.netmask="255.255.255.0"
						uci set network.radio0ap.ipv6=1
			
						uci set network.radio0sta="interface"
						uci set network.radio0sta.ifname="wlan0"
						uci set network.radio0sta.proto="dhcp"
						uci set network.radio0sta.ipv6=1
						
						uci commit network
		
					##################Wireless#########################
					 	#Delete interfaces
						uci delete wireless.radio0
						uci delete wireless.ap
						uci delete wireless.sta
						uci delete wireless.mesh
		
						#Add interfaces
						uci set wireless.radio0="wifi-device"
						uci set wireless.radio0.type="mac80211"
						uci set wireless.radio0.channel="auto"
						uci set wireless.radio0.phy="phy0"
						uci set wireless.radio0.disabled=0

						uci set wireless.ap="wifi-iface"
						uci set wireless.ap.device="radio0"
						uci set wireless.ap.mode="ap"
						uci set wireless.ap.network="radio0ap"
						uci set wireless.ap.encryption="psk2"
						uci set wireless.ap.disabled=1
						uci set wireless.ap.ssid="$(hostname)"
						uci set wireless.ap.key="$key_ap"
				
						uci set wireless.sta="wifi-iface"
						uci set wireless.sta.device="radio0"
						uci set wireless.sta.mode="sta"
						uci set wireless.sta.network="radio0sta"
						uci set wireless.sta.ssid="$ssid"
						uci set wireless.sta.encryption="$encryption"
						uci set wireless.sta.key="$key"
						uci set wireless.sta.disabled=0

					
						uci set wireless.mesh="wifi-iface"
						uci set wireless.mesh.device="radio0"
						uci set wireless.mesh.mode="mesh"
						uci set wireless.mesh.network="radio0"
						uci set wireless.mesh.mesh_id="ingerev"
						uci set wireless.mesh.encryption="psk2"
						uci set wireless.mesh.disabled=1
		
				
						uci commit wireless

						########DHCP config#############
						uci delete dhcp.radio0ap 
						
						uci commit dhcp 
											
					fi
		
				elif [ "$k" = "mode" ] && [ "$v" = "none" ]
				then 
					#logger "wifi" " none"
					uci set wireless.sta.disabled=1
					uci set wireless.ap.disabled=1
					uci set wireless.mesh.disabled=1

				fi
					

			done 

				unset $key	
				uci commit network 
				uci commit wireless
				#/etc/init.d/network restart 
				#/etc/init.d/wifi restart 
				echo '{"'$k'":"'$v'"}'	

                    ;;

		    restart_network)
			/etc/init.d/network restart
			/etc/init.d/wifi restart
		    ;; 

                    check_internet_connection)
                    # Ping google?
				 #logger -t "check" "internet connection"

                        if ping -c 5 8.8.8.8 &> /dev/null
                        then
                            uci set swupdated.common.automagically='on'
                            uci set swupdated.common.auto_expr='0 0 0 * * *'
                            uci commit swupdated

                            /etc/init.d/swupdated enable
                            /etc/init.d/swupdated restart  &> /dev/null
                            /etc/init.d/rtty enable
                            /etc/init.d/rtty restart &> /dev/null
                            /etc/init.d/sysntpd enable
                            /etc/init.d/sysntpd restart &> /dev/null
                            /etc/init.d/htpdate enable  
                            /etc/init.d/htpdate restart  &> /dev/null
                            /etc/init.d/ddns enable 
                            /etc/init.d/ddns restart  &> /dev/null
                            /etc/init.d/watchcat enable 
                            /etc/init.d/watchcat restart &> /dev/null  
			    echo '{"online":"true"}'
	

                        fi
			    echo '{"online":"false"}'

                    ;;
		    check_file_existence)
 			   read input;
                       	   json init
                       	   json_load "$input"
                           json_get_var path path
			   if [[ -f "$path" ]]; then
       				 echo '{"exists" : "true"}'
			   else
				 echo '{"exists" : "false"}'

			   fi			   

		    ;; 
		   compress_dir)
			   read input;
                       	   json init
                       	   json_load "$input"
                           json_get_var path path
			   json_get_var dst_path dst_path
			   if [[ -d "$path" ]]; then
				 #logger -t "Compress" "$path"
				 json_get_var name name
			 	 tar -czf "$name" "$path"
				if [[ -z "$dst_path" ]];then
					 mv "$name" /root/	  

				else
					mv "$name" "$dst_path"
					chmod 777 "$dst_path"/"$name"
				fi	
			   fi
			echo '{"done":"true"}'
		   ;;  

		  extract_dir)
		           read input;
                       	   json init
                       	   json_load "$input"
                           json_get_var path path
			   if [[ -f "$path" ]]; then
				 tar -xf archive.tar.gz
			   fi
			echo '{"done":"true"}'
		           read input;
                       	   json init
                       	   json_load "$input"
				

		   ;; 
		restore_backup) 
			  read input;
                 json init
                 json_load "$input"
			   json_get_var path path 
			if [[ ! -z "$path" ]];then
				sysupgrade -r "$path"
				echo '{"msg": "success"}'
			elif [[ -f "/root/backup.tar.bz2" ]];then 
				sysupgrade -r /root/backup.tar.bz2
				echo '{"msg": "success"}'		
			else
				echo '{"msg":"Backup not found"}'
			fi	
			
		   ;; 
		
		get_remote_file)
		 read input;
                json init
                json_load "$input"
			 json_get_var ip ip 
			 json_get_var name name
			 json_get_var delete_from_src delete_from_src
			 if [[ ! -z "$ip" ]] && [[ ! -z "$name" ]];then 
				#logger "wget " "$ip" "$name"
				cd /www/
				wget -O "$name" http://"$ip":8080/"$name"
				chmod 777 "$name"
			 fi 		

		   ;; 
		copy_file) 
		read input;
                json init
                json_load "$input"
			 json_get_var src_path src_path
			 json_get_var dst_path dst_path
			 json_get_var delete_from_src delete_from_src
			 if  [[ ! -z "$src_path" ]] && [[ ! -z "$dst_path" ]];then 
				cp "$src_path" "$dst_path"
				chmod 777 "$dst_path"
			 fi 		  
			 if [[ ! -z "$delete_from_src" ]] && [[ "$delete_from_src" = 1 ]];then
				#logger "he entrado a delete from src" "$delete_from_src" 

				rm "$src_path"
			 fi		

			
		   ;; 
		logread_remote)
			cd /www/
			logread > log.txt
			chmod 777 log.txt	
		  ;; 
		update_firmware) 
			/usr/sbin/webmanager_install_opkgs.sh  >/dev/null 2>/dev/null
		 ;;
		delete_file) 
		 read input;
                 json init
                 json_load "$input"
		 json_get_var path path 
		 logger "wizard" "enter to delete file"" $path"
		 files_allowed=$(echo "$path" | grep -E '.txt|.tar.gz|.tar.bz2|out' | grep -v "*")

		 if [[ ! -z "$files_allowed" ]];then
			logger "Deleting file  " "$path"
			rm "$path"
			
		 fi 
		if [[ "$path" == "/tmp/upgrade" ]];then
			logger "delete upgrade dir content"
			rm /tmp/upgrade/*
		fi
		
		 ;; 

		configure_update_period) 
		 read input;
           	 json init
           	 json_load "$input"
		 json_get_var period period 
		 files_allowed=$(echo "$path" | grep -E '.txt|.tar.gz|.tar.bz2' | grep -v "*")

		  if [[ "$period" == 1 ]];then
			logger "Daily software update configured  "
			uci set swupdated.common.automagically='on'
			uci set swupdated.common.auto_expr='0 0 0 * * *'
			uci commit swupdated
			/etc/init.d/swupdated restart
			uci set healthcheck.internet_connection.force_disable_swupdated="off"
			uci commit healthcheck
			/etc/init.d/healthcheck restart

		 elif [[ "$period" == 2 ]];then
			logger "Software update every 15 days "	
			uci set swupdated.common.automagically='on'
			uci set swupdated.common.auto_expr='0 0 0 */15 * *'
			uci commit swupdated
			/etc/init.d/swupdated restart 	
			uci set healthcheck.internet_connection.force_disable_swupdated="off"
			uci commit healthcheck
			/etc/init.d/healthcheck restart

		 elif [[ "$period" == 3 ]];then 
			logger "Monthly software update configured"
			uci set swupdated.common.automagically='on'
			uci set swupdated.common.auto_expr='0 0 0 1 * *'
			uci commit swupdated
			/etc/init.d/swupdated restart
			uci set healthcheck.internet_connection.force_disable_swupdated="off"
			uci commit healthcheck
			/etc/init.d/healthcheck restart

		 elif [[ "$period" == 4 ]];then
			logger "Quarterly software update configured"
			uci set swupdated.common.automagically='on'
			uci set swupdated.common.auto_expr='0 0 0 1 */3 *'
			uci commit swupdated
			/etc/init.d/swupdated restart
			uci set healthcheck.internet_connection.force_disable_swupdated="off"
			uci commit healthcheck
			/etc/init.d/healthcheck restart

		 elif [[ "$period" == 5 ]];then 
			logger "Semi-annual software update"
			uci set swupdated.common.automagically='on'
			uci set swupdated.common.auto_expr='0 0 0 1 */6 *'
			uci commit swupdated
			/etc/init.d/swupdated restart
			uci set healthcheck.internet_connection.force_disable_swupdated="off"
			uci commit healthcheck
			/etc/init.d/healthcheck restart

		 elif [[ "$period" == 6 ]];then 
			logger "Annual software update"
			uci set swupdated.common.automagically='on'
			uci set swupdated.common.auto_expr='0 0 0 1 1 *'
			uci commit swupdated 
			/etc/init.d/swupdated restart 
			uci set healthcheck.internet_connection.force_disable_swupdated="off"
			uci commit healthcheck
			/etc/init.d/healthcheck restart

		 elif [[ "$period" == 7 ]];then 
			logger "Don't update automatically"
			uci set swupdated.common.automagically='off'
			uci commit swupdated 
			/etc/init.d/swupdated restart
			uci set healthcheck.internet_connection.force_disable_swupdated="on"
			uci commit healthcheck
			/etc/init.d/healthcheck restart

		 fi 
		
		 ;;
		
		tests)
		read input;
           	json init
           	json_load "$input"
		 	json_get_var test test 
			logger "test " "$test"
			/etc/init.d/scpi_server restart
			sleep 1
			echo $test | telnet localhost:5000
			echo '{"done":"1"}'
			
		;;	
		
		generate_hash)
			read input;
           		json init
           		json_load "$input"
		 	json_get_var string string 
		 	json_get_var path path
			if [[ ! -z "$string" ]];then
				hash=$(echo "$string" | sha256sum | awk '{ print $1 }')
			elif [[ ! -z "$path" ]];then 
				hash=$(sha256sum "$path" | awk '{ print $1 }' )
			fi 
				echo '{"output":"'$hash'"}'
		;; 

		
		is_display_video_available)
			read input;
           		json init
           		json_load "$input"
		 	json_get_var url url
			a=$(echo ${url// /%20})
			out=$(curl -sI "$a")
			found=$(echo "$out" | grep "200 OK")
			if [[ ! -z "$found" ]];then
				logger "display video found"
				echo '{"found":"true"}'
			else
				logger "display video not found"
				echo '{"found":"false"}'

			fi	
		;;		 
		download_display_video) 
			read input;
           		json init
           		json_load "$input"
		 	json_get_var url url
			logger "download display video from " "$url"
			a=$(echo ${url// /%20})
		 	curl --header 'Content-Type: application/json' --data-binary '{"jsonrpc":"2.0","method":"Addons.ExecuteAddon","params":{"addonid":"script.ingeUpload.files","params":{"url":"'$a'"}},"id":1}' http://192.168.1.199:8080/jsonrpc  

		;;
		

		recipes_to_file)
			ls /etc/ingeruled/recipes/ > /tmp/recipes_list
		;;

		bpm_info)
			read input;
           		json init
           		json_load "$input"
		 	json_get_var canid canid
			json_get_var path path 
			logger "wizard: ""bpm_info called"
			./root/BPMs/bpm_info $canid > $path"/bpm_info"
			sed -i '1,6d' $path/bpm_info
	
		

		;;

		execute_script)
			read input;
           		json init
           		json_load "$input"
		 	json_get_var script script
			json_get_var sig sig 
			logger "wizard: ""Execute commands called"
			chmod +x "$script"
			chmod +x "$sig"
			if [[ -f "$script" ]]; then 
				logger "script exists"
			else 
				logger "script doesnt exist"
			fi
			logger "script:$script sig:$sig"
			/usr/bin/exec_web_signed_script.sh "$script" "$sig"  > /tmp/out
		

		;;
		sysupgrade)
	
			read input;
           		json init
           		json_load "$input"
		 	json_get_var sn sn

			logger "wizard: ""sysupgrade"
	
		 	name=$(ls /tmp/upgrade | grep rootfs)
			logger "name" "$name"
			
			ubus send "$sn".upgrade_from_local_dir '{"file": "/tmp/upgrade/'"$name"'"}'
	
			

		;;
		create_dir)
	
			read input;
           		json init
           		json_load "$input"
		 	json_get_var path path
			logger "wizard: ""create_dir"
		 	mkdir $path
		;;
		
		transferfiles_bg)
			read input;
           		json init
           		json_load "$input"
		 	json_get_var sn sn
		 	json_get_var path path

			logger "wizard: ""transferfiles_bg"  "$path" "$sn" "$dst_path"
			ubus call transferfiles send_file '{"path":"'"$path"'", "sn":"'"$sn"'", "dst_path":"'"$path"'"}'
		
						#ubus send "$sn".upgrade_from_local_dir '{"file": "/tmp/upgrade/'"$name"'"}'



		;;


		esac
	;;
esac
