package maker

import (
	"context"
	"os"
	"path/filepath"

	"gitea.loveuer.com/yizhisec/pkg3/logger"
	"yizhisec.com/hsv2/forge/internal/opt"
	"yizhisec.com/hsv2/forge/pkg/downloader"
)

// make proxy for 8443, 443
// by caddy, managed by systemd
// steps:
// 1. download caddy release binary: url(https://artifactory.yizhisec.com:443/artifactory/filestore/hsv2/bin/caddy)
// 2. generate caddyfile
// 3. generate systemd service file
func (m *maker) Proxy(ctx context.Context) error {
	const (
		binURL       = "https://artifactory.yizhisec.com:443/artifactory/filestore/hsv2/bin/caddy"
		caddyfileTpl = `:8443 {
    reverse_proxy __UPSTREAM_8443__
}

:443 {
    reverse_proxy __UPSTREAM_443__
}`
		systemdSvc = `[Unit]
Description=YiZhiSec Caddy Reverse Proxy
After=network.target

[Service]
Type=simple
User=root
ExecStart=/usr/local/bin/caddy run --config /etc/caddy/Caddyfile
StandardOutput=journal
StandardError=journal
Nice=-20
Restart=always
RestartSec=15

[Install]
WantedBy=multi-user.target`
	)

	location := filepath.Join(opt.Cfg.Make.Dir, "dependency", "proxy")

	logger.Info("☑️ maker.Proxy: 开始构建 caddy 反向代理...")
	logger.Debug("☑️ maker.Proxy: 创建目录 %s", location)
	if err := os.MkdirAll(location, 0755); err != nil {
		logger.Debug("❌ maker.Proxy: 创建目录失败: %v", err)
		return err
	}
	logger.Debug("✅ maker.Proxy: 创建目录 %s 成功", location)

	logger.Debug("☑️ maker.Proxy: 下载 caddy 二进制..., url = %s, dest = %s", binURL, filepath.Join(location, "caddy"))
	if err := downloader.Download(
		ctx,
		binURL,
		filepath.Join(location, "caddy"),
		downloader.WithInsecureSkipVerify(),
		downloader.WithFileMode(0755),
	); err != nil {
		logger.Debug("❌ maker.Proxy: 下载 caddy 失败, url = %s, err = %v", binURL, err)
		return err
	}
	logger.Debug("✅ maker.Proxy: 下载 caddy 成功, url = %s", binURL)

	logger.Debug("☑️ maker.Proxy: 写入 Caddyfile 文件..., dest = %s", filepath.Join(location, "Caddyfile"))
	if err := os.WriteFile(filepath.Join(location, "Caddyfile"), []byte(caddyfileTpl), 0644); err != nil {
		logger.Debug("❌ maker.Proxy: 写入 Caddyfile 失败, dest = %s, err = %v", filepath.Join(location, "Caddyfile"), err)
		return err
	}
	logger.Debug("✅ maker.Proxy: 写入 Caddyfile 文件成功, dest = %s", filepath.Join(location, "Caddyfile"))

	logger.Debug("☑️ maker.Proxy: 写入 caddy.service 文件..., dest = %s", filepath.Join(location, "caddy.service"))
	if err := os.WriteFile(filepath.Join(location, "caddy.service"), []byte(systemdSvc), 0644); err != nil {
		logger.Debug("❌ maker.Proxy: 写入 caddy.service 失败, dest = %s, err = %v", filepath.Join(location, "caddy.service"), err)
		return err
	}
	logger.Debug("✅ maker.Proxy: 写入 caddy.service 文件成功, dest = %s", filepath.Join(location, "caddy.service"))

	logger.Info("✅ maker.Proxy: 构建 caddy 反向代理成功!!!")
	return nil
}
