package main

// Dosya ucu yardımcıları: izinli kökler ve izinli uzantılar.

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"strings"
)

var izinliParametreler = map[string]bool{
	"search": true, "c": true, "p": true, "o": true, "j": true, "i": true,
	"w": true, "r": true, "m": true, "path_column": true, "date_created_column": true,
	"size_column": true, "date_modified_column": true, "sort": true, "ascending": true,
}

var izinliUzantilar = map[string]bool{".nc": true, ".txt": true, ".gcode": true}

// surucuKokleri: sistemde var olan tüm sürücülerin kökünü döner.
func surucuKokleri() []string {
	var kokler []string
	for harf := 'A'; harf <= 'Z'; harf++ {
		kok := fmt.Sprintf("%c:\\", harf)
		if _, err := os.Stat(kok); err == nil {
			kokler = append(kokler, kok)
		}
	}
	return kokler
}

func kokIzinliMi(yol string, kokler []string) bool {
	yolKucuk := strings.ToLower(yol)
	for _, kok := range kokler {
		onek := strings.ToLower(strings.TrimRight(filepath.Clean(kok), `\/`)) + string(filepath.Separator)
		if strings.HasPrefix(yolKucuk, onek) {
			return true
		}
	}
	return false
}

func dosyaSun(w http.ResponseWriter, r *http.Request, kokler []string) {
	yol := filepath.Clean(r.URL.Query().Get("yol"))
	if !izinliUzantilar[strings.ToLower(filepath.Ext(yol))] {
		http.Error(w, "izinli olmayan dosya türü", http.StatusForbidden)
		return
	}
	if !kokIzinliMi(yol, kokler) {
		http.Error(w, "izinli klasör dışında", http.StatusForbidden)
		return
	}
	dosya, err := os.Open(yol)
	if err != nil {
		http.Error(w, "dosya açılamadı", http.StatusNotFound)
		return
	}
	defer dosya.Close()
	bilgi, err := dosya.Stat()
	if err != nil || bilgi.IsDir() {
		http.Error(w, "geçersiz dosya", http.StatusBadRequest)
		return
	}
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.Header().Set("Cache-Control", "no-store")
	io.Copy(w, dosya)
}
