1#!/usr/bin/ksh
2#
3# This file and its contents are supplied under the terms of the
4# Common Development and Distribution License ("CDDL"), version 1.0.
5# You may only use this file in accordance with the terms of version
6# 1.0 of the CDDL.
7#
8# A full copy of the text of the CDDL should have accompanied this
9# source. A copy of the CDDL is also available via the Internet at
10# http://www.illumos.org/license/CDDL.
11
12# Copyright 2021 OmniOS Community Edition (OmniOSce) Association.
13
14set -o errexit -o pipefail
15trap 'echo Error occured at line $LINENO' ERR
16
17if [[ ! -v CODEMGR_WS ]] || (($# < 1)); then
18	cat <<- EOM
19This script should be run within a bldenv by issuing 'make update' in
20\$CODEMGR_WS/usr/src/data/zoneinfo
21	EOM
22	exit 1
23fi
24
25MANIFEST=$CODEMGR_WS/usr/src/pkg/manifests/system-data-zoneinfo.p5m
26PREFIX=usr/share/lib/zoneinfo
27
28if [[ ! -f "$MANIFEST" ]]; then
29	echo "Could not find $MANIFEST"
30	exit 1
31fi
32
33function find_cmd {
34	typeset cmd="$1"
35	typeset var=$(echo $cmd | tr '[:lower:]' '[:upper:]')
36	typeset -n path="$var"
37	path=$(whence -fp "$cmd")
38	if (($? != 0)) || [ ! -x "$path" ]; then
39		echo "Cannot find executable '$cmd' in PATH"
40		exit 1
41	fi
42}
43
44# This script uses a few commands which are not part of illumos and are
45# expected to be available in the path.
46find_cmd pkgfmt
47
48typeset -A links
49typeset -A targets
50for f in "$@"; do
51	if [[ ! -r "$f" ]]; then
52		echo "Could not read $f"
53		exit 1
54	fi
55	echo "+++ Processing input file $f"
56	grep '^Link' "$f" | tr -s '[:space:]' | \
57	    while IFS=$' \t' read _ tgt src _; do
58
59		osrc=$src
60		targets[$tgt]=1
61
62		printf "    %20s => %s\n" $src $tgt
63
64		while [[ $src == */* && ${src%%/*} == ${tgt%%/*} ]]; do
65			src=${src#*/}
66			tgt=${tgt#*/}
67		done
68
69		# On no matches, grep -o exits non-zero, hence the || true to
70		# satisfy the shell's errexit option.
71		sslashes=$(echo $src | grep -o / | wc -l || true)
72		r=
73		while ((sslashes-- > 0)); do
74			r+="../"
75		done
76		links[$osrc]="$r$tgt"
77	done
78done
79
80tmpf1=`mktemp`
81tmpf2=`mktemp`
82trap 'rm -f $tmpf1 $tmpf2' EXIT
83[[ -n "$tmpf1" && -f "$tmpf1" ]]
84[[ -n "$tmpf2" && -f "$tmpf2" ]]
85
86cp $MANIFEST $tmpf1
87$PKGFMT -u $tmpf1
88
89echo "+++ Removing existing hardlinks from manifest"
90egrep -v "^hardlink " $tmpf1 > $tmpf2
91mv $tmpf2 $tmpf1
92
93echo "+++ Removing existing targets from manifest"
94for i in "${!links[@]}" "${!targets[@]}"; do
95	egrep -v "^file path=$PREFIX/$i\$" $tmpf1 > $tmpf2
96	mv $tmpf2 $tmpf1
97done
98
99echo "+++ Adding new entries to manifest"
100{
101	for i in "${!targets[@]}"; do
102		echo "file path=$PREFIX/$i"
103	done
104	for i in "${!links[@]}"; do
105		echo "hardlink path=$PREFIX/$i target=${links[$i]}"
106	done
107} >> $tmpf1
108
109echo "+++ Formatting manifest"
110$PKGFMT -fv2 $tmpf1
111
112mv $tmpf1 $MANIFEST
113
114