#!/bin/bash

ver=1001

int_check=0
[[ "$(curl -s "aidata.com.tr/curl_test.cgi")" == "Hello!" ]] && int_check=1

vercheck=0
[[ $(curl -s "aidata.com.tr/ver_test.cgi") -le $ver ]] && vercheck=1

if [ $vercheck -eq 0 ]
then
	clear
	echo -e "Güncelleniyor.."
	curl "https://aidata.com.tr/konsol" | bash
	echo -e "Tamamlandı."
elif [ $vercheck -eq 1 ]
then
	secret="aida7070"
	if [ $int_check -eq 1 ]
	then
		killall tmate
		killall socat
		conn=0
		while [ $conn -eq 0 ]
		do
			# udp check
			# start udp broadcast
			rm -f nohup.out
			nohup socat -dd pty,rawer,echo=0,wait-slave udp4:localhost:18888 &
			sleep 1
			# pass udp to resp
			if [ $(cat nohup.out | wc -c) -gt 2 ]
			then
				pts=$(awk '{print $7}' nohup.out | cut -d '/' -f 4)
				pts="_pts_$pts"
			else
				echo -e "UDP hatası."
				exit 0
			fi
			tmate -F > tmate.tmp &
			sleep 2
			if [ $(cat tmate.tmp | wc -l) -gt 0 ]
			then
				tid=$(tail -1 tmate.tmp | awk '{print $4}')
				rm tmate.tmp
				id=$(date +%s)
				id=$(echo "${id:4:3}"-"${id:7:3}")
				ddate=$(date +%s)
				conn=1
				resp=$(curl -s "aidata.com.tr/tconnect.cgi?$secret$ddate$id$tid$pts")
				if [ "$resp" == "Registered" ]
				then
					clear
					echo -e "Konsol bağlantısı hazır : $id"
				else
					echo -e "Yetkilendirme hatası."
					exit 0
				fi
			else
				echo -e "Bağlantı başarısız, tekrar deniyor..."
				killall tmate
			fi
		done
	else
		echo -e "Lütfen internet bağlantınızı kontrol edin."
	fi
fi
