package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"strings"
	"syscall"

	"github.com/sevlyar/go-daemon"
)

// 获取客户端IP的函数
func getClientIP(r *http.Request) string {
	// 尝试从X-Forwarded-For头部获取IP
	forwarded := r.Header.Get("X-Forwarded-For")
	if forwarded != "" {
		// X-Forwarded-For可能包含多个IP地址，取第一个
		ips := strings.Split(forwarded, ",")
		return strings.TrimSpace(ips[0])
	}
	// 尝试从X-Real-Ip头部获取IP
	realIP := r.Header.Get("X-Real-Ip")
	if realIP != "" {
		return realIP
	}
	// 最后从RemoteAddr中获取IP
	return r.RemoteAddr
}

// 处理HTTP请求的函数
func handler(w http.ResponseWriter, r *http.Request) {
	clientIP := getClientIP(r)
	response := fmt.Sprintf("%s", clientIP)
	fmt.Fprintln(w, response)
	log.Printf("Handled request from %s\n", clientIP) // 记录日志
}

func main() {
	// 定义守护进程的启动配置
	cntxt := &daemon.Context{
		PidFileName: "inet-ip.pid",
		PidFilePerm: 0644,
		LogFileName: "inet-ip.log",
		LogFilePerm: 0640,
		WorkDir:     "./",
		Umask:       027,
		Args:        []string{"[inet-ip]"},
	}

	// 启动守护进程
	d, err := cntxt.Reborn()
	if err != nil {
		log.Fatal("Unable to run: ", err)
	}
	if d != nil {
		return
	}
	defer cntxt.Release()

	// 设置日志输出到文件
	logFile, err := os.OpenFile("inet-ip.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
	if err != nil {
		log.Fatalf("Error opening log file: %s", err)
	}
	defer logFile.Close()
	log.SetOutput(logFile)

	// 启动HTTP服务器
	go serveHTTP()

	// 创建一个通道来接收操作系统信号
	stop := make(chan os.Signal, 1)
	signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)

	log.Println("Server started")

	// 等待信号
	<-stop

	// 服务器停止时记录日志
	log.Println("Server stopped")
}

func serveHTTP() {
	http.HandleFunc("/", handler)
	fmt.Println("Starting server on :90")
	if err := http.ListenAndServe(":90", nil); err != nil && err != http.ErrServerClosed {
		log.Fatalf("Error starting server: %s", err)
	}
}
