#!/bin/sh
# TazPkg - Tiny autonomous zone packages manager, hg.slitaz.org/tazpkg
# getenv - TazPkg module
# Get TazPkg working environment


# Set up the aliases guaranteed to work with Busybox applets rather with the GNU Coreutils ones
# due to some incompatibilities.
# Please don't hesitate to expand or shrink this list (with justification).
for i in awk basename bzcat cat chmod chroot clear cmp cp cpio cut date dd diff dirname dpkg-deb \
	du egrep fgrep find grep gzip head httpd id ln ls lzcat md5sum mkdir mktemp mv readlink \
	realpath rm rmdir rpm rpm2cpio sed sort stat su tac tail tar tee touch tr tty uniq unlzma wc \
	wget which xzcat zcat; do
	alias $i="busybox $i"
done > /dev/shm/aliases$$

# You can force all busybox appets with :
# busybox --list-full | sed -e '/base64/d' \
#	-e 's|.*|readlink /& \| grep -q busybox \|\| echo $(basename &)|' | sh | \
# 	sed 's|.*|alias &="busybox &"|'  > /dev/shm/aliases$$
. /dev/shm/aliases$$
rm /dev/shm/aliases$$

. /lib/libtaz.sh

# Show debug messages
debug() {
	if [ -n "$debug" ]; then
		colorize 036 "$@" >&2
		[ -n "$LOG" ] && echo -e "$(date +%f) $@" >> "${LOG/.log/.debug}"
	fi
}

debug "\n========\n$0 '$1' '$2' '$3' '$4'"

# Check and re-create files and folders (if permissions enough)
missing_file() {
	if [ ! -f "$1" ]; then
		case $(id -u) in
			0)  mkdir -p "$(dirname "$1")"; touch "$1"
				[ -n "$2" ] && cp -a "$2" "$(dirname "$1")"
				;;
			*) _ 'Missing: %s' "$1" >&2; die 'Please run tazpkg as root.';;
		esac
	fi
}
missing_dir() {
	if [ ! -d "$1" ]; then
		case $(id -u) in
			0) mkdir -p "$1";;
			*) _ 'Missing: %s' "$1" >&2; die 'Please run tazpkg as root.';;
		esac
	fi
}

# Fill empty file with value
fill() {
	if [ ! -s "$1" ]; then
		case $(id -u) in
			0) echo "$2" > "$1";;
			*) _ 'File "%s" empty.' "$1" >&2; die 'Please run tazpkg as root.';;
		esac
	fi
}

# Escape BRE metacharacters so a package name (e.g. "llama.cpp") is safe to
# embed in a grep/sed pattern -- without this a "." matches any character.
# Backslashes first, then the bracket set (no "\" inside it, "]" leads).
reesc() { echo "$1" | sed -e 's/\\/\\\\/g' -e 's/[].[^$*]/\\&/g'; }




# Normalize $root
root="${root%/}"
debug "root        = '$root'"

# Setup main config files
missing_dir  "$root/etc/slitaz/"
missing_file "$root/etc/slitaz/slitaz.conf" '/etc/slitaz/slitaz.conf'
missing_file "$root/etc/slitaz/tazpkg.conf" '/etc/slitaz/tazpkg.conf'
missing_file "$root/etc/slitaz-release"; fill "$root/etc/slitaz-release" 'cooking'

# Read configuration
# WANTED_LANGS set in the environment, even empty, wins over slitaz.conf
unset env_langs_set
[ -n "${WANTED_LANGS+set}" ] && env_langs_set='yes' && env_langs="$WANTED_LANGS"
if [ -n "$root" ]; then
	# Patch external conf files to correctly handle --root value
	slitaz_conf=$(mktemp); cp "$root/etc/slitaz/slitaz.conf" "$slitaz_conf"
	tazpkg_conf=$(mktemp); cp "$root/etc/slitaz/tazpkg.conf" "$tazpkg_conf"
	sed -i "s| /| $root/|g; s|\"/|\"$root/|g" "$slitaz_conf" "$tazpkg_conf"
	. "$slitaz_conf"; . "$tazpkg_conf"
	rm "$slitaz_conf" "$tazpkg_conf"
else
	. /etc/slitaz/slitaz.conf; . /etc/slitaz/tazpkg.conf
fi
if [ -n "$env_langs_set" ]; then
	WANTED_LANGS="$env_langs"
elif [ -n "$root" ]; then
	# Target decides: only its WANTED_LANGS="..." line is read (same as spk)
	WANTED_LANGS="$(sed -n 's|^WANTED_LANGS=||p' "$root/etc/slitaz/slitaz.conf" \
		2>/dev/null | tail -n1)"
	case "$WANTED_LANGS" in
		\"*\"|\'*\') WANTED_LANGS="${WANTED_LANGS#?}"; WANTED_LANGS="${WANTED_LANGS%?}" ;;
	esac
fi
debug "WANTED_LANGS= '$WANTED_LANGS'"


# Compress stdin into the lzma file $1 the way cook does (xz --format=lzma);
# the lzma package's tool when xz is missing (none of them is a dependency)
lzma_to() {
	if command -v xz >/dev/null; then
		xz --format=lzma -6 -c > "$1"
	else
		lzma e "$1" -si
	fi
}


# Print the modifiers of list $1 that are still installed: spk-rm and older
# tazpkg left the name of a removed package behind
live_modifiers() {
	[ -s "$1" ] || return 0
	while read mod; do
		[ -f "$INSTALLED/$mod/receipt" ] && echo "$mod"
	done < "$1"
}


# Translations (bug 1064): a .mo is a files.list line matching this ERE
MO_RE='^/usr/share/locale/[^/]+/LC_MESSAGES/[^/]+\.mo$'

# Print the .mo lines of list $1, in its order
mo_list() { grep -E "$MO_RE" "$1"; }

# Print the .mo lines of list $2 that WANTED_LANGS keeps ($1 = keep)
# or drops ($1 = drop). Language part of a locale dir or a wanted code:
# cut at the first "_", "@" or ".". Empty WANTED_LANGS keeps all.
mo_filter() {
	awk -v mode="$1" -v w="$WANTED_LANGS" -v re="$MO_RE" '
	BEGIN {
		n = split(w, a, /[ \t\n]+/)
		for (i = 1; i <= n; i++) {
			if (a[i] == "") continue
			l = a[i]; sub(/[_@.].*/, "", l); want[l]; k++
		}
	}
	$0 ~ re {
		split($0, p, "/"); l = p[5]; sub(/[_@.].*/, "", l)
		if (!k || (l in want)) { if (mode == "keep") print }
		else if (mode == "drop") print
	}' "$2"
}

# Remove the lines of list $1 from files.list $2 and md5sum $3 (in place)
mo_unlist() {
	awk -v l="$1" 'FILENAME == l { d[$0]; next } !($0 in d)' "$1" "$2" > "$2.$$" &&
		cat "$2.$$" > "$2" && rm "$2.$$"
	[ -f "$3" ] || return 0
	awk -v l="$1" 'FILENAME == l { d[$0]; next }
		{ f = $0; sub(/^[^ ]*  /, "", f) } !(f in d)' "$1" "$3" > "$3.$$" &&
		cat "$3.$$" > "$3" && rm "$3.$$"
}

# Remove the files of list $1 under root $2, then their LC_MESSAGES and
# locale dirs when left empty
mo_delete() {
	local file
	while read file; do
		rm -f "$2$file"
		rmdir "$2${file%/*}" "$2${file%/*/*}" 2>/dev/null
	done < "$1"
	:
}

: ${LOG:=$SLITAZ_LOGS/tazpkg.log}

debug "PKGS_DB     = '$PKGS_DB'"
debug "INSTALLED   = '$INSTALLED'"
debug "SLITAZ_LOGS = '$SLITAZ_LOGS'"
debug "LOG         = '$LOG'"

# Blocked packages list shared with spk. Merge the old tazpkg list once.
BLOCKED="$PKGS_DB/blocked.list"
if [ -f "$PKGS_DB/blocked-packages.list" ] && [ "$(id -u)" -eq 0 ]; then
	cat "$PKGS_DB/blocked-packages.list" "$BLOCKED" 2>/dev/null | sort -u > "$BLOCKED.$$" \
		&& mv "$BLOCKED.$$" "$BLOCKED" && rm -f "$PKGS_DB/blocked-packages.list"
fi
debug "BLOCKED     = '$BLOCKED'"
UP_LIST="$PKGS_DB/packages.up"
debug "UP_LIST     = '$UP_LIST'"
debug "CACHE_DIR   = '$CACHE_DIR'"
SAVE_CACHE_DIR="$CACHE_DIR"


# Re-create TazPkg working folders and files
for dir in "$PKGS_DB" "$CACHE_DIR" "$INSTALLED" "$SLITAZ_LOGS"; do
	missing_dir "$dir"
done
for file in "$BLOCKED" "$UP_LIST" "$LOG" "$PKGS_DB/packages.info" "$PKGS_DB/mirror"; do
	missing_file "$file"
done
fill "$PKGS_DB/mirror" "${ONLINE_PKGS%/}/"


# Check for installed.info
info_path="$PKGS_DB/installed.info"
missing_file "$info_path"
if [ ! -s "$info_path" ]; then
	# Empty installed.info
	if [ -n "$(find "$INSTALLED" -name 'receipt')" ]; then
		# Some packages are installed
		if [ "$(id -u)" -eq 0 ]; then
			# Root can re-create installed.info
			_ 'File "%s" generated. Please wait...' 'installed.info' >&2
			for pkg in $(find "$INSTALLED" -name receipt); do
				unset PACKAGE VERSION EXTRAVERSION CATEGORY SHORT_DESC WEB_SITE \
					TAGS PACKED_SIZE UNPACKED_SIZE DEPENDS
				. $pkg
				SIZES=$(echo $PACKED_SIZE $UNPACKED_SIZE | sed 's|\.0||g')
				# remove newlines from some receipts
				DEPENDS=$(echo $DEPENDS)
				MD5="$(fgrep " $PACKAGE-$VERSION$EXTRAVERSION.tazpkg" "$PKGS_DB/installed.md5" | awk '{print $1}')"
				cat >> "$info_path" << EOT
$PACKAGE	$VERSION$EXTRAVERSION	$CATEGORY	$SHORT_DESC	$WEB_SITE	$TAGS	$SIZES	$DEPENDS	$MD5
EOT
			done
		else
			# User can't re-create installed.info
			fill "$info_path"
		fi
	fi
else
	# Non-empty installed.info

	# Check for md5 field (#9) in the installed.info: older version missed it
	if [ -n "$(awk -F$'\t' 'BEGIN{ n = "" } { if(NF != 9){ n = "o"; } } END{ print n }' $info_path)" ]; then
		if [ "$(id -u)" -eq 0 ]; then
			# Root can re-create it
			_n 'File "%s" generated. Please wait...' 'installed.info.new' >&2
			awk -F$'\t' -vm="$PKGS_DB/installed.md5" 'BEGIN{OFS="\t"}
			{
				if (NF != 9) {
					pkg = $1 "-" $2 ".tazpkg";
					"fgrep " pkg " " m " | cut -c-32" | getline $9;
					$9 = ($9 == "") ? "00000000000000000000000000000000" : $9;
				}
				print;
			}' $info_path > $info_path.new
			mv -f $info_path.new $info_path
			status
		else
			# User can't re-create it
			_ 'Old "%s".' 'installed.info' >&2; die 'Please run tazpkg as root.'
		fi
	fi
fi


# Check for packages.info
if [ ! -s "$PKGS_DB/packages.info" -a "$(id -u)" -eq 0 -a "$0" != '@@MODULES@@/recharge' ]; then
	@@MODULES@@/recharge >&2
fi



# Get repositories priority using $PKGS_DB/priority.
# In this file undigest repos are called by their names and main mirror by 'main'

PRIORITY="$(
{
	[ -s "$PKGS_DB/priority" ] && cat "$PKGS_DB/priority"
	echo 'main'
	[ -d "$PKGS_DB/undigest" ] && ls "$PKGS_DB/undigest"
} | awk -vv="$PKGS_DB/undigest/" '{
	if(arr[$0] != 1) { arr[$0]=1; print v $0; }
}' | sed 's|/undigest/main||')"

# spk extra repositories ($PKGS_DB/extra/<name>, managed by spk-mirror and
# spk-up) come first, extra/local before the others, as in spk
EXTRA_REPOS="$(
	for i in "$PKGS_DB/extra/local" "$PKGS_DB"/extra/*; do
		[ -f "$i/packages.info" ] && [ -s "$i/mirror" ] && echo "$i"
	done | awk '!seen[$0]++')"
[ -n "$EXTRA_REPOS" ] && PRIORITY="$EXTRA_REPOS
$PRIORITY"
debug "PRIORITY    = '$PRIORITY'"


# spk-up holds $PKGS_DB/.spk-up.lock (its pid inside) while it rewrites the
# shared lists: an upgrade or recharge now would interleave writes. Only
# those two: receipt hooks run by spk-up do call "tazpkg install".
case "${0##*/}" in
	upgrade|recharge)
		lock_pid="$(cat "$PKGS_DB/.spk-up.lock/pid" 2>/dev/null)"
		if [ -n "$lock_pid" ] && grep -qs spk-up "/proc/$lock_pid/cmdline"; then
			_ 'spk-up is running (pid %s), try again later.' "$lock_pid" >&2
			exit 1
		fi ;;
esac


# TazPkg version
export VERSION=$(awk -F$'\t' '$1=="tazpkg"{print $2;exit}' "$PKGS_DB/installed.info")
# User Agent
export UA="TazPkg-${VERSION:-Unknown}"
debug "UA          = '$UA'"

CUR_DIR="$(pwd)"


debug '-- end getenv --'
