# working in a temp directory ...

file delete -force -- tmpdir[pid]

# extract everything from current binary

file copy [info nameofexecutable] tmpdir[pid]

# remove unwanted stuff from tmpdir[pid]

# ... TODO (adapt it to your requirements)
# here let's keep the bare minimum

apply {keep {
    foreach name [glob -tails -dir tmpdir[pid] *] {
        if {$name in $keep} {
            continue
        }
        file delete -force -- [file join tmpdir[pid] $name]
    }
}} [list tcl8.6 tk8.6 sdl2tk8.6]

file mkdir [file join tmpdir[pid] app]

# add app code to tmpdir[pid]/app, at least a main.tcl
# is required which provides the entry point

# ... TODO (example given)

apply {name {
    set f [open $name w]
    # a very small app ...
    puts $f "button .b -text {Press Me} -command exit ; pack .b"
    close $f
}} [file join tmpdir[pid] app main.tcl]

# rebuild a new binary, stripping the temp directory in all file names

if {$tcl_platform(platform) eq "windows"} {
    zipfs::mkimg myapp.exe tmpdir[pid] tmpdir[pid]
} else {
    zipfs::mkimg myapp tmpdir[pid] tmpdir[pid]
}

# remove the temp directory

file delete -force -- tmpdir[pid]

# try to start the new binary if it is a wish
# otherwise stdin would be needed and we can't
# run in background.

if {[info command winfo] eq "winfo"} {
    if {$tcl_platform(platform) eq "windows"} {
        catch {exec [file join [pwd] myapp.exe] < NUL: &}
    } else {
        catch {exec [file join [pwd] myapp] < /dev/null &}
    }
}

# done

exit

