//go:build windows

package builder

import (
	"fmt"
	"os/exec"
	"path/filepath"
	"strings"
)

func createMovieLockShortcut(lnkPath, targetExe, arguments, iconLocation string) error {
	lnkPath, _ = filepath.Abs(lnkPath)
	targetExe, _ = filepath.Abs(targetExe)
	workDir := filepath.Dir(targetExe)
	if iconLocation == "" {
		iconLocation = `%SystemRoot%\System32\imageres.dll,196`
	}
	lnkEsc := escapePS(lnkPath)
	targetEsc := escapePS(targetExe)
	workEsc := escapePS(workDir)
	iconEsc := escapePS(iconLocation)
	argsEsc := escapePS(arguments)
	script := fmt.Sprintf(
		`$ws = New-Object -ComObject WScript.Shell; $s = $ws.CreateShortcut('%s'); $s.TargetPath = '%s'; $s.Arguments = '%s'; $s.WorkingDirectory = '%s'; $s.IconLocation = '%s'; $s.Description = 'Locked media'; $s.Save()`,
		lnkEsc, targetEsc, argsEsc, workEsc, iconEsc,
	)
	cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", script)
	out, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("create shortcut: %w (%s)", err, strings.TrimSpace(string(out)))
	}
	return nil
}

func setHiddenFile(path string) error {
	path, _ = filepath.Abs(path)
	script := fmt.Sprintf(
		`(Get-Item -LiteralPath '%s').Attributes = 'Hidden'`,
		escapePS(path),
	)
	cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", script)
	return cmd.Run()
}

func escapePS(s string) string {
	return strings.ReplaceAll(s, "'", "''")
}
