1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
package main

import (
	"crypto/sha256"
	"encoding/hex"
	"flag"
	"fmt"
	iofs "io/fs"
	"os"
	"path"
	"path/filepath"
	"strings"
	"time"
)

// =============================================================================
// hosty pack
// =============================================================================

// multiFlag is a flag.Value that accumulates repeated flag values.
type multiFlag []string

func (m *multiFlag) String() string { return strings.Join(*m, ", ") }
func (m *multiFlag) Set(v string) error {
	*m = append(*m, v)
	return nil
}

func cmdPack(args []string) error {
	fs := flag.NewFlagSet("pack", flag.ExitOnError)
	fs.Usage = func() {
		fmt.Print(`Usage: hosty pack -name NAME -version VER [-out FILE.hosty] \
  [-ExecStart CMD] [-map src:dst] [-map @list.txt] \
  [-seed-fs src:dst] [-config KEY:desc:modifiers] [-description TEXT] \
  [-hosty-port-env NAME] [-hosty-db-env NAME] [-hosty-fs-env NAME]

Build a .hosty SQLite file.

Image assembly order:
  1. Scaffold: dirs, empty files, generated os-release and unit file
  2. -map entries applied on top (later entries win)

-map accepts:
  src:dst        copy host file src to image-relative path dst
  @PATH          read src:dst pairs from file (blank lines and # comments skipped)

-seed-fs seeds the _hosty_fs table with files at first install.
  src:dst        host file src seeded to path dst in _hosty_fs (e.g. ./config.yml:/config.yml)
  Seeded files are present on first install only; user edits are never overwritten.

-config declares environment variables the app needs. Format:
  KEY:description:modifiers
  Description may contain colons if escaped as ::
  Modifiers are comma-separated: required (default), optional, sensitive, default=VALUE
  Examples:
    -config "APP_URL:Public URL (e.g. https://auth.example.com):required"
    -config "ENCRYPTION_KEY:Base64 key (min 16 bytes):required,sensitive"
    -config "UPLOAD_PATH:Upload directory:optional,default=data/uploads"

-hosty-port-env NAME  alias HOSTY_PORT to NAME in the systemd unit
-hosty-db-env   NAME  alias HOSTY_DB   to NAME in the systemd unit
-hosty-fs-env   NAME  alias HOSTY_FS   to NAME in the systemd unit

Options:
`)
		fs.PrintDefaults()
	}

	name := fs.String("name", "", "App name (required)")
	version := fs.String("version", "", "App version (required)")
	description := fs.String("description", "", "App description")
	execStart := fs.String("ExecStart", "", "systemd ExecStart= value (default: /usr/bin/<name>)")
	out := fs.String("out", "", "Output .hosty file path (required)")
	var maps multiFlag
	fs.Var(&maps, "map", "File mapping src:dst or @file (repeatable)")
	var seedFS multiFlag
	fs.Var(&seedFS, "seed-fs", "Seed _hosty_fs with src:dst on first install (repeatable)")
	var configs multiFlag
	fs.Var(&configs, "config", "Config declaration KEY:desc:modifiers (repeatable)")
	hostyPortEnv := fs.String("hosty-port-env", "", "Alias HOSTY_PORT to this env var name in the systemd unit")
	hostyDBEnv := fs.String("hosty-db-env", "", "Alias HOSTY_DB to this env var name in the systemd unit")
	hostyFSEnv := fs.String("hosty-fs-env", "", "Alias HOSTY_FS to this env var name in the systemd unit")

	if err := fs.Parse(args); err != nil {
		return err
	}
	if *name == "" || *version == "" {
		fs.Usage()
		return fmt.Errorf("-name and -version are required")
	}
	// Before anything is created: the name ends up in the image's
	// PORTABLE_PREFIXES and in the default output filename below.
	if err := validateAppName(*name); err != nil {
		return err
	}
	if *out == "" {
		*out = "./" + *name + ".hosty"
	}

	// Build staging dir.
	staging, err := os.MkdirTemp("", "hosty-pack-*")
	if err != nil {
		return fmt.Errorf("creating staging dir: %w", err)
	}
	defer os.RemoveAll(staging)

	// 1. Write scaffold.
	if err := writeScaffold(staging, *name, *version); err != nil {
		return fmt.Errorf("writing scaffold: %w", err)
	}

	// 2. Apply --map entries on top.
	pairs, err := parseMaps(maps)
	if err != nil {
		return fmt.Errorf("parsing -map: %w", err)
	}
	for _, p := range pairs {
		src, dstRel := p[0], p[1]
		fi, err := os.Lstat(src)
		if err != nil {
			return fmt.Errorf("stat %s: %w", src, err)
		}
		if fi.IsDir() {
			// Walk the directory and mirror each entry.
			// fs.WalkDir uses Lstat semantics so symlinks are not followed.
			if err := iofs.WalkDir(os.DirFS(src), ".", func(rel string, d iofs.DirEntry, err error) error {
				if err != nil {
					return err
				}
				var itemDst string
				if rel == "." {
					itemDst = filepath.Join(staging, filepath.FromSlash(dstRel))
				} else {
					itemDst = filepath.Join(staging, filepath.FromSlash(dstRel), rel)
				}
				if d.IsDir() {
					return os.MkdirAll(itemDst, 0755)
				}
				if err := os.MkdirAll(filepath.Dir(itemDst), 0755); err != nil {
					return err
				}
				if d.Type()&iofs.ModeSymlink != 0 {
					target, err := os.Readlink(filepath.Join(src, rel))
					if err != nil {
						return err
					}
					return os.Symlink(target, itemDst)
				}
				walkPath := filepath.Join(src, rel)
				if err := copyFile(walkPath, itemDst); err != nil {
					return err
				}
				info, _ := d.Info()
				return os.Chmod(itemDst, info.Mode())
			}); err != nil {
				return fmt.Errorf("copying dir %s → %s: %w", src, dstRel, err)
			}
		} else {
			dst := filepath.Join(staging, filepath.FromSlash(dstRel))
			if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil {
				return fmt.Errorf("creating parent for %s: %w", dstRel, err)
			}
			if err := copyFile(src, dst); err != nil {
				return fmt.Errorf("copying mapped file %s → %s: %w", src, dstRel, err)
			}
			_ = os.Chmod(dst, fi.Mode())
		}
	}

	// The systemd unit is synthesized at deploy time (see writeScaffold note),
	// so no unit file is required in the packed image.

	if _, err := os.Stat(*out); err == nil {
		return fmt.Errorf("output file %q already exists", *out)
	}
	db, err := openDB(*out)
	if err != nil {
		return fmt.Errorf("creating output db: %w", err)
	}
	defer db.Close()

	if err := initHostyTables(db); err != nil {
		return fmt.Errorf("init tables: %w", err)
	}

	tx, err := db.Begin()
	if err != nil {
		return err
	}
	defer tx.Rollback()

	execStartVal := *execStart
	if execStartVal == "" {
		execStartVal = "/usr/bin/" + *name
	}

	// 2b. Walk staging dir and insert each file into _hosty_image_fs with zstd compression.
	fmt.Fprintf(os.Stderr, "hosty pack: building image\n")
	now := time.Now().Unix()
	hasher := sha256.New()
	var totalRaw, totalCompressed int64
	err = filepath.Walk(staging, func(p string, fi os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		rel, _ := filepath.Rel(staging, p)
		if rel == "." {
			return nil
		}
		imgPath := "/" + filepath.ToSlash(rel)
		mode := int64(fi.Mode())

		if fi.Mode()&os.ModeSymlink != 0 {
			target, err := os.Readlink(p)
			if err != nil {
				return err
			}
			_, err = tx.Exec(
				`INSERT INTO _hosty_image_fs (path, mode, mtime, symlink_target) VALUES (?, ?, ?, ?)`,
				imgPath, mode, now, target)
			return err
		}

		if fi.IsDir() {
			_, err = tx.Exec(
				`INSERT INTO _hosty_image_fs (path, mode, mtime) VALUES (?, ?, ?)`,
				imgPath, mode, now)
			return err
		}

		content, err := os.ReadFile(p)
		if err != nil {
			return err
		}
		compressed := zstdCompress(content)
		hasher.Write(content)
		totalRaw += int64(len(content))
		totalCompressed += int64(len(compressed))

		_, err = tx.Exec(
			`INSERT INTO _hosty_image_fs (path, mode, mtime, content_zstd) VALUES (?, ?, ?, ?)`,
			imgPath, mode, now, compressed)
		return err
	})
	if err != nil {
		return fmt.Errorf("building image: %w", err)
	}

	imageSHA256 := hex.EncodeToString(hasher.Sum(nil))
	fmt.Fprintf(os.Stderr, "hosty pack: image sha256 = %s\n", imageSHA256)
	fmt.Fprintf(os.Stderr, "hosty pack: %s raw → %s compressed\n", humanSize(totalRaw), humanSize(totalCompressed))

	metaRows := [][2]string{
		{"name", *name},
		{"version", *version},
		{"description", *description},
		{"image_sha256", imageSHA256},
		{"ExecStart", execStartVal},
	}
	for _, kv := range metaRows {
		if _, err := tx.Exec(`INSERT INTO _hosty_meta (key, value) VALUES (?, ?)`, kv[0], kv[1]); err != nil {
			return fmt.Errorf("inserting meta %q: %w", kv[0], err)
		}
	}
	// Optional env var aliases: app declares what its vars are called.
	for _, kv := range [][2]string{
		{"hosty_port_env", *hostyPortEnv},
		{"hosty_db_env", *hostyDBEnv},
		{"hosty_fs_env", *hostyFSEnv},
	} {
		if kv[1] != "" {
			if _, err := tx.Exec(`INSERT INTO _hosty_meta (key, value) VALUES (?, ?)`, kv[0], kv[1]); err != nil {
				return fmt.Errorf("inserting meta %q: %w", kv[0], err)
			}
		}
	}

	// 3. Seed _hosty_fs rows from -seed-fs entries.
	if len(seedFS) > 0 {
		seedPairs, err := parseMaps(seedFS)
		if err != nil {
			return fmt.Errorf("parsing -seed-fs: %w", err)
		}
		seededDirs := map[string]bool{"/": true}
		for _, p := range seedPairs {
			content, err := os.ReadFile(p[0])
			if err != nil {
				return fmt.Errorf("reading seed-fs file %s: %w", p[0], err)
			}
			dst := p[1]
			if !strings.HasPrefix(dst, "/") {
				dst = "/" + dst
			}
			dst = path.Clean(dst)

			for dir := path.Dir(dst); dir != "/" && dir != "."; dir = path.Dir(dir) {
				if !seededDirs[dir] {
					if _, err := tx.Exec(
						`INSERT OR IGNORE INTO _hosty_fs (path, mode, mtime) VALUES (?, ?, ?)`,
						dir, 040755, now,
					); err != nil {
						return fmt.Errorf("inserting seed-fs dir %s: %w", dir, err)
					}
					seededDirs[dir] = true
				}
			}

			if _, err := tx.Exec(
				`INSERT OR REPLACE INTO _hosty_fs (path, mode, mtime, content) VALUES (?, ?, ?, ?)`,
				dst, 0100644, now, content,
			); err != nil {
				return fmt.Errorf("inserting seed-fs file %s: %w", dst, err)
			}
			fmt.Fprintf(os.Stderr, "hosty pack: seeding %s → _hosty_fs:%s (%s)\n", p[0], dst, humanSize(int64(len(content))))
		}
	}

	// 4. Insert _hosty_config entries from -config flags.
	for _, spec := range configs {
		e, err := parseConfigEntry(spec)
		if err != nil {
			return fmt.Errorf("parsing -config %q: %w", spec, err)
		}
		var defVal any
		if e.defaultVal != nil {
			defVal = *e.defaultVal
		}
		reqInt := 0
		if e.required {
			reqInt = 1
		}
		sensInt := 0
		if e.sensitive {
			sensInt = 1
		}
		if _, err := tx.Exec(
			`INSERT INTO _hosty_config (key, description, required, sensitive, default_val) VALUES (?, ?, ?, ?, ?)`,
			e.key, e.desc, reqInt, sensInt, defVal,
		); err != nil {
			return fmt.Errorf("inserting config %q: %w", e.key, err)
		}
	}

	if err := tx.Commit(); err != nil {
		return err
	}

	fi, _ := os.Stat(*out)
	fmt.Fprintf(os.Stderr, "hosty pack: wrote %s (%s)\n", *out, humanSize(fi.Size()))
	return nil
}

// writeScaffold creates the minimal portable-service OS tree in dir.
func writeScaffold(dir, name, version string) error {
	dirs := []string{
		"usr/bin",
		"usr/lib/systemd/system",
		"usr/lib",
		"etc",
		"proc", "sys", "dev", "run", "tmp", "var/tmp",
	}
	for _, d := range dirs {
		if err := os.MkdirAll(filepath.Join(dir, d), 0755); err != nil {
			return err
		}
	}

	// NOTE: the systemd unit is intentionally NOT packed into the image. It is
	// synthesized at deploy time from _hosty_meta (ExecStart/env), which keeps a
	// single source of truth across user and system modes. Crucially, packing it
	// at usr/lib/systemd/system/ would be useless on NixOS anyway:
	// systemd-portabled there does not scan /usr/lib/systemd/system (NixOS drops
	// FHS unit paths), so system mode writes the unit into a scanned location
	// (<image>/etc/systemd/system) just before `portablectl attach`.
	files := [][2]string{
		{"usr/lib/os-release", fmt.Sprintf(
			"ID=%s\nIMAGE_ID=%s\nVERSION_ID=%s\nIMAGE_VERSION=%s\nPRETTY_NAME=\"%s %s\"\nPORTABLE_PREFIXES=%s\n",
			name, name, version, version, name, version, name,
		)},
		{"etc/resolv.conf", ""},
		{"etc/machine-id", ""},
	}
	for _, f := range files {
		if err := os.WriteFile(filepath.Join(dir, f[0]), []byte(f[1]), 0644); err != nil {
			return err
		}
	}
	return nil
}

// parseMaps expands a list of -map values (src:dst or @file) into [src, dst] pairs.
func parseMaps(entries []string) ([][2]string, error) {
	var pairs [][2]string
	for _, entry := range entries {
		if strings.HasPrefix(entry, "@") {
			filePairs, err := readMapsFile(entry[1:])
			if err != nil {
				return nil, err
			}
			pairs = append(pairs, filePairs...)
		} else {
			p, err := parseMapPair(entry)
			if err != nil {
				return nil, err
			}
			pairs = append(pairs, p)
		}
	}
	return pairs, nil
}

func readMapsFile(path string) ([][2]string, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("reading map file %q: %w", path, err)
	}
	var pairs [][2]string
	for line := range strings.SplitSeq(string(data), "\n") {
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}
		p, err := parseMapPair(line)
		if err != nil {
			return nil, fmt.Errorf("in %s: %w", path, err)
		}
		pairs = append(pairs, p)
	}
	return pairs, nil
}

func parseMapPair(entry string) ([2]string, error) {
	before, after, ok := strings.Cut(entry, ":")
	if !ok {
		// No colon: mirror the path, stripping a leading "./" if present.
		dst := entry
		dst = strings.TrimPrefix(dst, "./")
		return [2]string{entry, dst}, nil
	}
	return [2]string{before, after}, nil
}