summaryrefslogtreecommitdiff
path: root/drain
blob: c739b124b3892d37a49677bb68a067db017f3df7 (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
97
98
99
#!/usr/bin/env bash
# Copyright 2016 Luke Shumaker
# This work is free. You can redistribute it and/or modify it under the
# terms of the Do What The Fuck You Want To Public License, Version 2,
# as published by Sam Hocevar. See the COPYING file for more details.

# The user should not call this script directly.

declare -r workdir=/var/lib/pristine-etc

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

pacman-all-name-arch() {
	LC_ALL=C pacman -Qni | 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 "$workdir"
	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

	ln -sr etc.git etc/.git

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

pull() (
	cd /etc
	git remote add pristine "${workdir}/etc" &>/dev/null || true
	git fetch pristine
)

lock() {
	local fd=$1
	local file=$2
	eval "exec $fd>"'"$file"'
	flock "${@:3}" "$fd"
}

unlock() {
	local fd=$1
	exec {fd}>&-
}

main() {
	set -e -o pipefail
	umask 0022

	if ! lock 7 "${workdir}/etc.lock" -n; then
		return 0
	fi
	while true; do
		lock 8 "${workdir}/spool.lock"
		if ! [[ -f "${workdir}/spool" ]]; then
			return 0
		fi
		msg="$(cat "${workdir}/spool")"
		rm -f "${workdir}/spool"
		unlock 8

		commit "$msg"
		pull
	done
}

main "$@"