package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"regexp"
	"strings"
)

func main() {

	if len(os.Args) != 4 {
		fmt.Println("Wrong usage")
		return
	}

	url := "http://172.20.9.13/auth-service/oauth/token"

	payload := strings.NewReader("------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"username\"\r\n\r\nsystemphone\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"password\"\r\n\r\nsystem@voip\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"grant_type\"\r\n\r\npassword\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"scope\"\r\n\r\nread\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--")

	//fmt.Println("bss called for token")
	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW")
	req.Header.Add("authorization", "Basic ZnJvbnRlbmQ6dmVyeS1zZWNyZXQ=")
	req.Header.Add("cache-control", "no-cache")
	req.Header.Add("postman-token", "ff5ec4ca-4c85-11d2-ef50-fa14e76e3170")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)

	//	fmt.Println(res)
	//	fmt.Println(string(body))

	tokentmp := string(body)

	re := regexp.MustCompile("(n\":\")(.*?)(,)")

	out := re.FindAllString(tokentmp, -1)

	token := ""

	for _, i := range out {

		token = strings.TrimLeft(strings.TrimRight(i, "\","), "n\":\"")

	}

	uniq := os.Args[1]
	cid := os.Args[2]
	number := os.Args[3]

	url2 := fmt.Sprintf("http://172.20.9.13/bss-service/api/interactions/phone?id=%v&agent_ext=%v&caller_num=%v", uniq, cid, number)

	//url2 := "http://192.168.35.249:8000/bss-service/api/interactions/phone?id=1592305878.497&agent_ext=217&caller_num=09121430917"

	//url2 := fmt.Sprintf("http://192.168.35.249:8000/bss-service/api/interactions/phone?id=%v&agent_ext=%v&caller_num=%v", uniq, cid, number)

	req, _ = http.NewRequest("POST", url2, nil)

	bearer := fmt.Sprintf("bearer %v", token)
	fmt.Printf("\nbss token %v\n", bearer)

	req.Header.Add("authorization", bearer)
	req.Header.Add("cache-control", "no-cache")
	req.Header.Add("postman-token", "2d7de42a-f60c-b748-63ad-a9fec8f343ef")

	res, _ = http.DefaultClient.Do(req)

	res.Body.Close()
	body, _ = ioutil.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println("bss popup response:", string(body))

}
