package main

import (
	"b612.me/starlog"
	"b612.me/starnet"
	"b612.me/staros"
	"errors"
	"fmt"
	"net/url"
	"os"
	"path/filepath"
)

func main() {
	myDir := filepath.Dir(os.Args[0])
	baseName := filepath.Base(os.Args[0])
	procs, err := staros.FindProcessByName(baseName)
	if err != nil {
		starlog.Errorln(err)
		os.Exit(2)
	}
	for _, v := range procs {
		if int(v.Pid) == os.Getpid() {
			continue
		}
		if len(v.Args) > 1 {
			starlog.Errorf("another process already run:%+v\n", v)
			os.Exit(3)
		}
	}
	if len(os.Args) < 2 {
		pid, err := staros.Daemon(os.Args[0], "-f")
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		fmt.Println("pid :", pid)
		return
	}
	starlog.SetLogFile(filepath.Join(myDir, "icbcauth.log"), starlog.Std, true)
	defer starlog.Close(starlog.Std)
	//sig := make(chan os.Signal)
	//signal.Notify(sig, os.Kill, os.Interrupt)
	//for {
	data, err := CheckNeedAuth(starlog.Std)
	if err != nil {
		return
	}
	if data != nil {
		err = Auth(starlog.Std, data)
		if err != nil {
			return
		}
	}
	//		return
	//		select {
	//		case <-sig:
	//			starlog.Infoln("Stopped By Signal")
	//			return
	//		case <-time.After(time.Second * 300):
	//		}
	//	}
}

func CheckNeedAuth(log *starlog.StarLogger) (*url.URL, error) {
	log.Noticeln("Checking If Need Auth")
	res, err := starnet.Curl(starnet.NewRequests("http://139.199.163.65/", nil, "GET",
		starnet.WithDisableRedirect(true)))
	if err != nil {
		log.Errorln("Checking Failed:", err)
		return nil, err
	}
	if res.Location != nil {
		log.Warningln("Checking Finished:Need Auth,Auth Url:", res.Location.String())
		return res.Location, nil
	}
	log.Infoln("Checking Finished,No Need Auth")
	return nil, nil
}

func Auth(log *starlog.StarLogger, authUrl *url.URL) error {
	log.Noticeln("Trying to Auth...")
	strUrl := "http://" + authUrl.Host + "/portallogin?" + authUrl.RawQuery
	log.Noticeln("Auth Url is:", strUrl)
	res, err := starnet.Curl(starnet.NewRequests(strUrl, nil, "GET",
		starnet.WithDisableRedirect(true)))
	if err != nil {
		log.Errorln("Auth Failed:", err)
		return err
	}
	if res.Location == nil {
		starlog.Errorln("Cannot Got Redirect Url")
		return errors.New("Cannot Got Redirect Url")
	}
	starlog.Infoln("Redirect Url is:", res.Location.String())
	starlog.Noticeln("Getting Cookie...")
	cok, err := starnet.Curl(starnet.NewRequests(res.Location.String(), nil, "GET"))
	if err != nil {
		log.Errorln("Auth Failed:", err)
		return err
	}
	if len(cok.RespCookies) == 0 {
		log.Errorln("Cannot Got Cookies")
		return errors.New("Get Cookie Failed")
	}
	starlog.Infoln("Got Cookie:", cok.RespCookies)
	starlog.Noticeln("Trying to Using Auth Url:", `http://content.icbc.com.cn/cmp/AuthSkipController.do?method=authSkip&ajaxRequest=true`)
	res, err = starnet.Curl(starnet.NewRequests(`http://content.icbc.com.cn/cmp/AuthSkipController.do?method=authSkip&ajaxRequest=true`,
		nil, "GET", starnet.WithDisableRedirect(true),
		starnet.WithHeader("Referer", res.Location.String()),
		starnet.WithCookies(cok.RespCookies)))
	if err != nil {
		log.Errorln("Auth Failed:", err)
		return err
	}
	log.Infoln("Auth Result:", res.RespHttpCode, string(res.RecvData))
	return nil
}
