package main

import (
	"log"
	"os"
	"os/exec"
	"strings"
	"sync"
	"time"
)

var (
	userInitiated   bool
	userInitiatedMu sync.Mutex
)

func monitorPID() {
	for {
		lastPID := readPID()
		currentPID := getPID()

		if currentPID != "" {
			if currentPID != lastPID {
				log.Printf("%s: PID changed: %s -> %s", time.Now(), lastPID, currentPID)
				log.Printf("%s: Running Blocklist update", time.Now())

				userInitiatedMu.Lock()
				force := 0
				if userInitiated {
					force = 1
				}
				userInitiatedMu.Unlock()

				updateBlocklist(force)

				time.Sleep(2 * time.Second)
				currentPID = getPID()
				writePID(currentPID)
			}
		} else {
			configMu.RLock()
			processName := config.ProcessName
			configMu.RUnlock()
			log.Printf("%s: %s not running!", time.Now(), processName)
			writePID("")
		}

		configMu.RLock()
		checkInterval := config.CheckInterval
		configMu.RUnlock()
		time.Sleep(time.Duration(checkInterval) * time.Second)
	}
}

func readPID() string {
	configMu.RLock()
	pidFile := config.PidFile
	configMu.RUnlock()

	data, err := os.ReadFile(pidFile)
	if err != nil {
		return ""
	}
	return strings.TrimSpace(string(data))
}

func writePID(pid string) {
	configMu.RLock()
	pidFile := config.PidFile
	configMu.RUnlock()

	os.WriteFile(pidFile, []byte(pid), 0644)
}

func getPID() string {
	configMu.RLock()
	processName := config.ProcessName
	configMu.RUnlock()

	cmd := exec.Command("pgrep", "-f", processName)
	out, err := cmd.Output()
	if err != nil {
		return ""
	}
	return strings.TrimSpace(string(out))
}
