// Command tl-patcher: copies TechLockdown's Supervise_bin and binary-patches
// the hard-coded "/var/run/usbmuxd" path to "/tmp/mitm-usbmux" (exact 16 bytes).
// Then ad-hoc re-signs so macOS will allow execution.
//
// Result: a patched binary that connects to our proxy unix-socket instead of
// the real usbmuxd daemon — without needing sudo or env-vars.
//
// Usage:
//
//	./bin/rebreak-tl-patcher
//	# Then run: /tmp/Supervise_bin_proxy
package main

import (
	"bytes"
	"fmt"
	"io"
	"os"
	"os/exec"
)

const (
	defaultSrc   = "/Users/chahinebrini/Downloads/TechLockdown-supervise-mac-arm64.app/Contents/MacOS/Supervise_bin"
	defaultDst   = "/tmp/Supervise_bin_proxy"
	origPath     = "/var/run/usbmuxd" // 16 bytes
	patchedPath  = "/tmp/mitm-usbmux" // 16 bytes ✓
)

func main() {
	src := defaultSrc
	dst := defaultDst
	if len(os.Args) > 1 {
		src = os.Args[1]
	}
	if len(os.Args) > 2 {
		dst = os.Args[2]
	}

	if len(origPath) != len(patchedPath) {
		fmt.Fprintf(os.Stderr, "ERROR: path lengths must match — orig=%d patched=%d\n", len(origPath), len(patchedPath))
		os.Exit(1)
	}

	fmt.Printf("Reading %s ...\n", src)
	data, err := os.ReadFile(src)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	count := bytes.Count(data, []byte(origPath))
	fmt.Printf("Found %d occurrence(s) of %q\n", count, origPath)
	if count == 0 {
		fmt.Fprintln(os.Stderr, "no patch needed?")
		os.Exit(1)
	}

	patched := bytes.ReplaceAll(data, []byte(origPath), []byte(patchedPath))

	fmt.Printf("Writing patched binary to %s ...\n", dst)
	if err := os.WriteFile(dst, patched, 0o755); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	// Remove quarantine xattr (otherwise macOS blocks unsigned launch)
	fmt.Println("Removing quarantine xattr ...")
	exec.Command("xattr", "-d", "com.apple.quarantine", dst).Run() // ignore err

	// Ad-hoc re-sign (otherwise macOS refuses to launch patched binary)
	fmt.Println("Removing original signature ...")
	out, err := exec.Command("codesign", "--remove-signature", dst).CombinedOutput()
	if err != nil {
		fmt.Printf("  warn: codesign remove: %v %s\n", err, out)
	}
	fmt.Println("Ad-hoc re-signing ...")
	out, err = exec.Command("codesign", "-f", "-s", "-", dst).CombinedOutput()
	if err != nil {
		fmt.Printf("  warn: codesign sign: %v %s\n", err, out)
	}

	// Show how to launch
	stat, _ := os.Stat(dst)
	size := int64(0)
	if stat != nil {
		size = stat.Size()
	}
	fmt.Printf("\nDone. Patched binary: %s (%d bytes)\n", dst, size)
	fmt.Printf("Path patch: %q → %q\n", origPath, patchedPath)
	fmt.Println()
	fmt.Println("Next steps:")
	fmt.Println("  1. In Terminal 1: ./bin/rebreak-usbmux-proxy -proxy /tmp/mitm-usbmux")
	fmt.Println("  2. In Terminal 2: " + dst)
	fmt.Println("  3. If macOS blocks: System Settings → Privacy & Security → 'Allow anyway'")
}

// suppress unused-import warning
var _ = io.Copy
