summaryrefslogtreecommitdiff
path: root/pristine-etc-keeper
blob: a8a39546ac9ea3dc6a928c29f1398ae161c394cd (plain)
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
#!/usr/bin/env bash
# Copyright 2016 Luke Shumaker
#
# This script gets called by the etckeeper post-install hook.

# TODO: better error handling

pacman-etc-name-ver() {
	LC_ALL=C pacman -Qo /etc | sed 's|^/etc/ is owned by ||'
}

pacman-all-name-arch() {
	LC_ALL=C pacman -Qi | tr $'\n' $'\r' | sed 's/\r\r/\n/g' | sed -r 's|(.*\r)?Name\s*:\s*(\S+)(\r.*)?\rArchitecture\s*:\s*(\S+)\r.*|\2 \4|'
}

commit() (
	local msg="$1"

	cd /var/lib/pristine-etc
	if ! [[ -d etc.git ]]; then
		mkdir -p etc
		(cd etc && etckeeper init -d "$PWD")
		mv etc/.git etc.git
		ln -sr etc.git etc/.git
	fi

	rm -rf etc/

	local err=false
	local files=()
	while IFS=' ' read -r pkgname pkgver arch; do
		local file=("/var/cache/pacman/pkg/$pkgname-$pkgver-$arch".pkg.tar.*)
		if ! test -f "$file"; then
			printf "ERROR: no cached package for %s %s %s\n" "$pkgname" "$pkgver" "$arch"
			err=true
		fi
		files+=("$file")
	done < <(join <(pacman-etc-name-ver|sort) <(pacman-all-name-arch|sort))
	if $err; then
		return 1
	fi
	local file
	for file in "${files[@]}"; do
		printf " -> %s\n" "$file"
		bsdtar xpvf "$file" etc
	done

	touch etc/.gitignore
	ln -sr etc.git etc/.git

	cd etc/
	if etckeeper unclean -d "$PWD"; then
		etckeeper commit -d "$PWD" "$msg"
	fi
)

pull() (
	cd /etc
	git remote add pristine /var/lib/pristine-etc/etc &>/dev/null || true
	git fetch pristine
)

lock() {
	exec 8>/var/lib/pristine-etc/lock
	flock -x -n 8
}

unlock() {
	exec 8>&-
}

main() {
	set -e
	umask 0022

	if [[ $# -gt 0 ]]; then
		lock
		printf '%s\n' "$*" >> /var/lib/pristine-etc/spool
		unlock
	fi

	while true; do
		lock
		if ! [[ -f /var/lib/pristine-etc/spool ]]; then
			return 0
		fi
		msg="$(cat /var/lib/pristine-etc/spool)"
		rm -f /var/lib/pristine-etc/spool
		unlock

		commit "$msg" || return $?
		pull || return $?
	done
}

main "$@"