Files
panic-cli/internal/software/app_image.go

139 lines
2.8 KiB
Go

package software
import (
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
)
type AppImage struct {
Path string
}
func (a *AppImage) GetCurrentPath() string {
return filepath.Join(a.Path, "current")
}
func (a *AppImage) GetReleasePath() (string, error) {
path := a.GetCurrentPath()
return os.Readlink(path)
}
func (a *AppImage) GetReleasePathForVersion(version string) string {
return filepath.Join(a.Path, "Releases/"+version+".AppImage")
}
func (a *AppImage) Install(version string, data io.Reader) error {
destPath := a.Path + "/Releases/" + version + ".AppImage"
tmpPath := destPath + ".part"
out, err := os.Create(tmpPath)
if err != nil {
return fmt.Errorf("could not create file: %w", err)
}
defer out.Close()
if _, err := io.Copy(out, data); err != nil {
return fmt.Errorf("download interrupted: %w", err)
}
out.Close() // Close before rename
if err := os.Chmod(tmpPath, 0755); err != nil {
return err
}
if err := os.Rename(tmpPath, destPath); err != nil {
return err
}
return a.Link(version)
}
func (a *AppImage) Link(version string) error {
target := a.GetReleasePathForVersion(version)
link := filepath.Join(a.Path, "current")
tmpLink := filepath.Join(a.Path, "current_tmp")
os.Remove(tmpLink)
if err := os.Symlink(target, tmpLink); err != nil {
return fmt.Errorf("failed to create temp link: %w", err)
}
if err := os.Rename(tmpLink, link); err != nil {
// If rename fails, clean up the temp link
os.Remove(tmpLink)
return fmt.Errorf("failed to update symlink: %w", err)
}
return nil
}
func (a *AppImage) Launch() error {
binary := a.GetCurrentPath()
cmd := exec.Command(binary)
cmd.SysProcAttr = &syscall.SysProcAttr{
Setsid: true,
}
cmd.Stdout = nil
cmd.Stderr = nil
cmd.Stdin = nil
if err := cmd.Start(); err != nil {
return fmt.Errorf("failed to start app: %w", err)
}
if err := cmd.Process.Release(); err != nil {
return err
}
fmt.Println("🚀 Launched in background. Bye!")
return nil
}
func (a *AppImage) GetVersion() (string, error) {
path := a.Path + "/current"
tempDir, err := os.MkdirTemp("", "panic-extrac-*")
if err != nil {
return "", err
}
defer os.RemoveAll(tempDir)
extractCmd := exec.Command(path, "--appimage-extract", "*.desktop")
extractCmd.Dir = tempDir
if err := extractCmd.Run(); err != nil {
return "", err
}
squashDir := filepath.Join(tempDir, "squashfs-root")
files, err := filepath.Glob(filepath.Join(squashDir, "*.desktop"))
if err != nil {
return "", err
}
if len(files) == 0 {
return "", fmt.Errorf("no desktop file found")
}
content, err := os.ReadFile(files[0])
if err != nil {
return "", err
}
lines := strings.Split(string(content), "\n")
for _, line := range lines {
if strings.Contains(line, "Version=") {
return strings.TrimSpace(strings.Split(line, "=")[1]), nil
}
}
return "", fmt.Errorf("version not found")
}