package main

import (
	"embed"
	"fmt"
	"io"
	"io/fs"
	"net"
	"net/http"
	"os"
	"os/exec"
	"os/signal"
	"path/filepath"
	"runtime"
	"syscall"
	"time"

	"golang.org/x/net/proxy"
)

//go:embed bin/nym-socks5-client-linux-amd64
var nymBin embed.FS

// nymdropProviderAddr is the Nym network requester — set at build time via -ldflags
var nymdropProviderAddr = "NYMDROP_PROVIDER_ADDR_PLACEHOLDER"

// nymdropInboxAddr is the Nym address of the nymdrop-server SP — set at build time via -ldflags
var nymdropInboxAddr = "NYMDROP_INBOX_ADDR_PLACEHOLDER"

func main() {
	// Extract nym-socks5-client binary to temp dir
	tmpDir, err := os.MkdirTemp("", "nymdrop-*")
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %v\n", err)
		os.Exit(1)
	}
	defer os.RemoveAll(tmpDir)

	nymBinName := "nym-socks5-client"
	if runtime.GOOS == "windows" {
		nymBinName += ".exe"
	}
	nymBinPath := filepath.Join(tmpDir, nymBinName)

	srcName := "bin/nym-socks5-client-linux-amd64"
	data, err := fs.ReadFile(nymBin, srcName)
	if err != nil {
		fmt.Fprintf(os.Stderr, "embedded binary not found: %v\n", err)
		os.Exit(1)
	}
	if err := os.WriteFile(nymBinPath, data, 0700); err != nil {
		fmt.Fprintf(os.Stderr, "extract binary: %v\n", err)
		os.Exit(1)
	}

	// Init nym client config if not already done
	homeDir, _ := os.UserHomeDir()
	configDir := filepath.Join(homeDir, ".nymdrop-source")
	initCmd := exec.Command(nymBinPath, "init", "--id", "nymdrop-source",
		"--provider", nymdropProviderAddr,
		"--home", configDir)
	initCmd.Stdout = os.Stdout
	initCmd.Stderr = os.Stderr
	_ = initCmd.Run() // ignore error if already initialised

	// Start nym-socks5-client
	nymCmd := exec.Command(nymBinPath, "run", "--id", "nymdrop-source",
		"--home", configDir,
		"--port", "11080")
	nymCmd.Stdout = os.Stdout
	nymCmd.Stderr = os.Stderr
	if err := nymCmd.Start(); err != nil {
		fmt.Fprintf(os.Stderr, "nym start: %v\n", err)
		os.Exit(1)
	}
	defer nymCmd.Process.Kill()

	// Wait for SOCKS5 to be ready
	fmt.Println("Connecting to Nym mixnet...")
	for i := 0; i < 30; i++ {
		conn, err := net.DialTimeout("tcp", "127.0.0.1:11080", 300*time.Millisecond)
		if err == nil {
			conn.Close()
			break
		}
		time.Sleep(500 * time.Millisecond)
	}

	// Serve submission form locally
	mux := http.NewServeMux()
	mux.HandleFunc("/", serveForm)
	mux.HandleFunc("/submit", handleSubmit)

	srv := &http.Server{Addr: "127.0.0.1:18080", Handler: mux}
	go srv.ListenAndServe()

	// Open browser
	openBrowser("http://127.0.0.1:18080")
	fmt.Println("NymDrop ready — http://127.0.0.1:18080")

	// Wait for interrupt
	sig := make(chan os.Signal, 1)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
	<-sig
	fmt.Println("\nShutting down.")
}

func openBrowser(url string) {
	switch runtime.GOOS {
	case "linux":
		exec.Command("xdg-open", url).Start()
	case "darwin":
		exec.Command("open", url).Start()
	case "windows":
		exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
	}
}

func serveForm(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.Header().Set("Cache-Control", "no-store")
	fmt.Fprint(w, submissionForm)
}

func handleSubmit(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}
	r.Body = http.MaxBytesReader(w, r.Body, 10*1024*1024)
	defer r.Body.Close()

	payload, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "read error", http.StatusBadRequest)
		return
	}
	defer func() {
		for i := range payload {
			payload[i] = 0
		}
	}()

	if len(payload) == 0 {
		http.Error(w, "empty payload", http.StatusBadRequest)
		return
	}

	dialer, err := proxy.SOCKS5("tcp", "127.0.0.1:11080", nil, proxy.Direct)
	if err != nil {
		fmt.Fprintf(os.Stderr, "socks5 dialer: %v\n", err)
		http.Error(w, "internal error", http.StatusInternalServerError)
		return
	}

	conn, err := dialer.Dial("tcp", nymdropInboxAddr)
	if err != nil {
		fmt.Fprintf(os.Stderr, "nym dial: %v\n", err)
		http.Error(w, "delivery failed", http.StatusBadGateway)
		return
	}
	defer conn.Close()

	if _, err := conn.Write(payload); err != nil {
		fmt.Fprintf(os.Stderr, "nym send: %v\n", err)
		http.Error(w, "delivery failed", http.StatusBadGateway)
		return
	}

	w.WriteHeader(http.StatusOK)
	w.Write([]byte("ok"))
}

const submissionForm = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NymDrop — Secure Submission</title>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{background:#0d1117;color:#c9d1d9;font-family:'Courier New',monospace;min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:2rem 1rem}
.card{background:#161b22;border:1px solid #21262d;border-radius:8px;padding:2.5rem 2rem;width:100%;max-width:580px}
h1{font-size:1.4rem;color:#e6edf3;letter-spacing:.15em;margin-bottom:.3rem}
.sub{font-size:.72rem;color:#484f58;margin-bottom:1.5rem}
.badges{display:flex;gap:.5rem;margin-bottom:1.8rem;flex-wrap:wrap}
.badge{font-size:.65rem;padding:.2rem .6rem;border-radius:20px;font-weight:bold}
.bg{background:rgba(0,255,160,.08);color:#00ffa0;border:1px solid rgba(0,255,160,.2)}
.bb{background:rgba(0,128,255,.08);color:#58a6ff;border:1px solid rgba(0,128,255,.2)}
.bn{background:rgba(255,255,255,.04);color:#8b949e;border:1px solid #30363d}
label{display:block;font-size:.72rem;color:#8b949e;margin-bottom:.4rem;text-transform:uppercase;letter-spacing:.08em}
textarea{width:100%;height:160px;background:#0d1117;border:1px solid #30363d;border-radius:6px;color:#c9d1d9;font-family:'Courier New',monospace;font-size:.88rem;padding:.9rem;resize:vertical;margin-bottom:1.4rem;outline:none}
textarea:focus{border-color:#00ffa0}
.fl{margin-bottom:1.8rem}
.fl-btn{display:inline-block;background:#21262d;border:1px solid #30363d;border-radius:6px;color:#8b949e;font-size:.78rem;padding:.5rem 1rem;cursor:pointer}
#file{display:none}
#fn{font-size:.72rem;color:#58a6ff;margin-left:.6rem}
button{width:100%;background:linear-gradient(135deg,#00ffa0,#0080ff);border:none;border-radius:6px;color:#0d1117;font-family:'Courier New',monospace;font-size:.9rem;font-weight:bold;letter-spacing:.1em;padding:.85rem;cursor:pointer;text-transform:uppercase}
#st{margin-top:1rem;font-size:.78rem;text-align:center;color:#00ffa0;min-height:1.2rem}
hr{border:none;border-top:1px solid #21262d;margin:2rem 0 1.2rem}
.note{font-size:.68rem;color:#3d444d;line-height:1.7}
</style>
</head>
<body>
<div class="card">
<h1>⬡ NYMDROP</h1>
<p class="sub">Anonymous submission — encrypted in your browser, delivered over Nym mixnet.</p>
<div class="badges">
<span class="badge bg">END-TO-END ENCRYPTED</span>
<span class="badge bb">NYM MIXNET</span>
<span class="badge bn">NO LOGS</span>
<span class="badge bn">NO METADATA</span>
</div>
<form id="f">
<label for="msg">Message</label>
<textarea id="msg" placeholder="Write your message here..."></textarea>
<div class="fl">
<label>Attachment (optional)</label>
<label class="fl-btn" for="file">📎 Choose file</label>
<input type="file" id="file">
<span id="fn"></span>
</div>
<button type="submit">🔒 Submit securely</button>
</form>
<div id="st"></div>
<hr>
<p class="note">Your submission is encrypted before leaving your device. The server keeps no logs. Once delivered over Nym, no record exists on this server.</p>
</div>
<script>
document.getElementById('file').onchange=function(){document.getElementById('fn').textContent=this.files.length?this.files[0].name:''};
const PUB='NYMDROP_PUBKEY_PLACEHOLDER';
async function h2b(h){const b=new Uint8Array(h.length/2);for(let i=0;i<h.length;i+=2)b[i/2]=parseInt(h.substr(i,2),16);return b}
document.getElementById('f').onsubmit=async function(e){
e.preventDefault();
const st=document.getElementById('st');
st.className='';st.textContent='Encrypting...';
try{
let pt=document.getElementById('msg').value;
const fi=document.getElementById('file');
if(fi.files.length){const fb=await fi.files[0].arrayBuffer();pt+='\n---FILE:'+fi.files[0].name+'---\n'+btoa(String.fromCharCode(...new Uint8Array(fb)))}
const sk=await crypto.subtle.importKey('raw',await h2b(PUB),{name:'ECDH',namedCurve:'X25519'},false,[]);
const ep=await crypto.subtle.generateKey({name:'ECDH',namedCurve:'X25519'},true,['deriveKey','deriveBits']);
const sb=await crypto.subtle.deriveBits({name:'ECDH',public:sk},ep.privateKey,256);
const hk=await crypto.subtle.importKey('raw',sb,'HKDF',false,['deriveKey']);
const ak=await crypto.subtle.deriveKey({name:'HKDF',hash:'SHA-256',salt:new Uint8Array(32),info:new TextEncoder().encode('nymdrop-v1')},hk,{name:'AES-GCM',length:256},false,['encrypt']);
const iv=crypto.getRandomValues(new Uint8Array(12));
const ct=await crypto.subtle.encrypt({name:'AES-GCM',iv},ak,new TextEncoder().encode(pt));
const er=await crypto.subtle.exportKey('raw',ep.publicKey);
const pkt=new Uint8Array(32+12+ct.byteLength);
pkt.set(new Uint8Array(er),0);pkt.set(iv,32);pkt.set(new Uint8Array(ct),44);
const r=await fetch('/submit',{method:'POST',headers:{'Content-Type':'application/octet-stream'},body:pkt});
if(r.ok){document.getElementById('f').reset();document.getElementById('fn').textContent='';st.textContent='Delivered. No record of this submission exists on the server.'}
else{st.className='error';st.textContent='Delivery failed. Try again.';}
}catch(err){st.className='error';st.textContent='Encryption failed: '+err.message}};
</script>
</body>
</html>`
