#!/bin/sh
# Variables set to build a Slint ISO, some common to build-installer.sh to
# avoid uselessly edit it.
CWD=$(pwd)
cd .. 1>/dev/null ||  exit 1
ROOTDIR=$(pwd)
export ROOTDIR
cd - 1>/dev/null || exit 1
PKGNAM=slint-installer # Instead of slackware-installer in Slackware
KVER=6.12.8
export KVER
export PKGNAM
SLACKROOT="/data/repos/slackware-15.0"
SLACKREPO="$SLACKROOT"/slackware64
export SLACKREPO
PATCHES="$SLACKROOT"/patches/packages
SLINTREPO="/repo/x86_64/slint-15.0/slint"
ARCH="$(uname -m)"
SOURCE="/repo/x86_64/slint-15.0/source"
export SOURCE
ISOVERSION="15.0-6"
ISOLABEL="SLINT$ISOVERSION"
export ISOLABEL
SLINTVERSION="15.0"
export SLINTVERSION
SLACKVERSION="15.0"
export SLACKVERSION
REGULARUSER="$(stat -c %U "$CWD")"
export REGULARUSER
DEST="$ROOTDIR"/installer-tree
ISODIR=/home/didier/iso64
export ISODIR
SCRIPTS="$ROOTDIR"/files-in-initrd
DATESTAMP="$(date -u +%Y%m%d)"
PATHTOISO=/repo/x86_64/slint-15.0/iso/slint64-"${ISOVERSION}".iso
INSTALLERVERSION=15.0
export INSTALLERVERSION
SLINTDOCS=/data/github/slint-translations
WIP="$ROOTDIR"/wip
LANG=C
[ "$(findmnt /data)" = "" ] && echo "/data is not mounted." && exit
initsources() {
rm -rf "$WIP"
mkdir "$WIP"
cp -r "$SLINTDOCS"/* "$WIP/"
}
update_main_scripts() {
	# We need the versions of the scripts functions and rc.S source of
	# the auto.pot and rc.S.pot files stored on Crowdin as sources
	# of the translations (po files) from which we generate the mo
	# files put in the installer-translations package that we will
	# install in the initrd
	cd "$WIP"/sources || exit 1
	cp rc.S/rc.S auto/functions SeTkeymap/SeTkeymap "$CWD"/files-in-initrd
	cd "$CWD" || exit 1
}
extract_doc_installer_from_HandBook() {
rm -f "$ROOTDIR"/doc/*html
cd "$WIP"/HandBook/ || exit 1
for handbookpo in *.HandBook.po; do
	ll_TT="${handbookpo%.*.*}"
	echo "generating $ll_TT.adoc..." 
	rm -f "$ll_TT".adoc
	po4a-translate -M UTF-8 -m "$WIP"/sources/HandBook/HandBook.adoc -f asciidoc -p "$handbookpo" -l "${handbookpo%po}"adoc
	handbook="${handbookpo%po}"adoc
	rm -f "${ll_TT}".adoc
done
rm -f en_US.adoc
cp "$WIP"/sources/HandBook/HandBook.adoc en_US.HandBook.adoc
for handbook in *.HandBook.adoc; do
	ll_TT="${handbook%.*.*}"
	echo "$ll_TT ..."
	sleep 3
	{
	echo \
":toc: left
:toclevels: 1
:toc-title: 
" >> "${ll_TT}".adoc
	# Chapter Overview of Slint installation
	sed -n '\@// Overview@,\@// Usage@p' "$handbook"|head -n -1
	# Chapter Usage of the installer
	sed -n "\@// Usage_installer@,\@// Encryption@p" "$handbook"|head -n -1
	# Chapter Prepare partitions for Slnt
	sed -n '\@// Prepare@,\@// Installation@p' "$handbook"
	# Chapter Encryption
	sed -n "\@// Encryption@,\@// Speakup@p" "$handbook"|head -n -1
	# Chapter Speakup
	sed -n "\@// Speakup@,\@// First_steps@p" "$handbook"| head -n -1
	# Chapter first steps
	sed -n "\@// First_steps@,\@// Usage@p" "$handbook"|head -n -1
	sed -n '\@// Glossary@,$p' "$handbook"
	} >> "${ll_TT}".adoc
	# Chapter Glossary.
	# Normalize the headers' levels not the same in the installer doc as in the HandBook
	sed 's/^== /==== /' "${ll_TT}".adoc > bof && mv bof "${ll_TT}".adoc
	sed 's/^===== /=== /' "${ll_TT}".adoc > bof && mv bof "${ll_TT}".adoc
	sed 's/^==== /== /' "${ll_TT}".adoc > bof && mv bof "${ll_TT}".adoc
	asciidoctor "${ll_TT}".adoc
	mv "${ll_TT}".html "$CWD"/doc
done
cd "$CWD" || exit 1
}

build_installer_translations() {
PRGNAM=installer-translations
BUILD=$(date -u +%Y%m%d)
ARCH=noarch
TMP=/tmp/build-installer-translations
rm -rf $TMP
PKG=$TMP/package-$PRGNAM
OUTPUT="$ROOTDIR"/packages
rm -rf  $PKG
mkdir -p "$PKG"/wip

# Build the PO files
# We first need to format the PO files in such a way that msggrep will
# work. msggrep ignores references like:

# File: <source file name>, line: <line number>

# But expects instead:
#: <source file name>:<line number>
#
# shellcheck disable=SC1090
. "$ROOTDIR"/files-in-initrd/SeTlocales
cd "$WIP"/auto || exit 1
for i in *po; do
sleep 1
  sed "/^#/{s/# File: /#: /;s/, line:[ ]*/:/}" "$i" > "$PKG"/wip/"$i"
  msggrep -o "$PKG"/"${i%%.*}"."${DOMAINNAME}".po -N ./*auto "$PKG"/wip/"$i"
done
cd "$WIP"/rc.S || exit 1
for i in *po; do
  sed "/^#/{s/# File: /#: /;s/, line:[ ]*/:/}" "$i" > "$PKG"/wip/"$i"
  msggrep -o "$PKG"/"${i%%.*}"."${DOMAINNAME}".po -N ./*rc.S "$PKG"/wip/"$i"
done
cd "$WIP"/SeTkeymap || exit 1
for i in *SeTkeymap.po; do
  sed "/^#/{s/# File: /#: /;s/, line:[ ]*/:/}" "$i" > "$PKG"/wip/"$i"
  msggrep -o "$PKG"/"${j%%.*}"."${DOMAINNAME}".po -N ./*SeTkeymap "$PKG"/wip/"$i"
done
cd "$WIP"/slint-scripts || exit 1
for i in *slint-scripts.po; do
  sed "/^#/{s/# File: /#: /;s/, line:[ ]*/:/}" "$i" > "$PKG"/wip/"$i"
  msggrep -o "$PKG"/"${j%%.*}"."${DOMAINNAME}".po -N ./*slint-scripts "$PKG"/wip/"$i"
done
cd "$PKG"/wip || exit 1
# Compile the message catalogs
# We will use translated strings tagged fuzzy.
for k in auto rc.S SeTkeymap slint-scripts; do
	DOMAINNAME=$k
	for j in *"$k".po; do
		ll_TT="${j%%.*}"
		SeTLocaleDir
		# running SeTLocaleDir sets LocaleDir
		# shellcheck disable=SC2154
		if [ "$LocaleDir" = "missing" ]; then
			printf %b "I don't know where to install the message catalog for ${ll_TT}.\n"
			printf %b "Please request that the file $CWD/files-ib-initrd/SeTlocales be completed\n"
			exit
		fi
		MO_DIR="$PKG"/usr/share/locale/"$LocaleDir"/LC_MESSAGES
		mkdir -p "$MO_DIR"
		msgfmt --strict -c -v -f --statistics -o "$MO_DIR"/"${DOMAINNAME}".mo "$j" 2>&1|tee error
		if ! grep -q " translated messages" error; then
			translated=0
		else
			grep "^.*$j: " error > stat
			translated=$(sed "s@.*: @@;s@ .*@@" stat)
		fi
		if ! grep -q "untranslated" stat; then
			untranslated=0
		else
			untranslated=$(sed "s@.* translated message[s]\{0,1\}, @@;s@ .*@@" stat)
			total=$((translated+untranslated))
			percentage=$((translated*100/total))
			if [ $percentage -lt 85 ]; then
				rm "$MO_DIR"/"${DOMAINNAME}".mo
				echo "$j rejected, only ${percentage}% translated."
			else
				chown root:root "$MO_DIR"/"${DOMAINNAME}".mo
				chmod 644 "$MO_DIR"/"${DOMAINNAME}".mo
			fi
		fi
	done
done
cd "$CWD" || exit 1
rm -rf "$PKG"/wip
rm -f "$PKG"/*po
mkdir -p "$PKG"/install
cat << EOF > "$PKG"/install/slack-desc
                      |-----handy-ruler------------------------------------------------------|
installer-translations: installer-translations (translations of messages in Slint installer)
installer-translations:
installer-translations: This package contains translations of messages displayed by
installer-translations: configurations scripts included in the Slint installer, thanks to the
installer-translations: translators of the Slint project. Visit our website: http://slint.fr
installer-translations:
installer-translations:
installer-translations:
installer-translations:
installer-translations:
EOF
rm -f "$OUTPUT"/"$PRGNAM"*txz
( cd $PKG || exit 1
/sbin/makepkg -l y -c n "$OUTPUT"/"$PRGNAM"-"$SLINTVERSION"-"$ARCH"-"${BUILD}"slint.txz
)
}
### The functions below are called when while building the installer 
add_packages() {
	# Do not add kernel-firmware, in the hope to help booting in EFI mode...
	# lbzip2 is a dependancey of file, more and pcre2grep
	# lz4 is a dependency of zstd.
	# libcre2.32.so.0 is requested by brltty.installer
	# liblouis is requested by brltty.installer
	# gc and gpm are dependencies of w3m
	# alsamixer needs libformw.so.5 shipped in the ncurses package.
	# dbus and libnl3 are needed by wireless-tools.
	# $ISODIR/slint/alsa-lib*.t?z replaced by the previous version in
	# $ISODIR/slint/alsa-utils*.t?z replaced by the previous version "$CWD"/packages
#installpkg --terse -root "$DEST" $ISODIR/slint/acl-*txz
#exit
	installpkg --terse -root "$DEST" \
	$ISODIR/slint/acl-*txz \
	$ISODIR/slint/dracut*txz \
	$ISODIR/slint/file*txz \
	$ISODIR/slint/sonic*txz \
	$ISODIR/slint/pcaudiolib*txz \
	$ISODIR/slint/bzip2*txz \
	$ISODIR/slint/gpm*txz \
	$ISODIR/slint/bluez-5*txz \
	$ISODIR/slint/bluez-firmware*txz \
	$ISODIR/slint/gc-*txz \
	$ISODIR/slint/dialog-*.t?z \
	$ISODIR/slint/expat*.t?z \
	$ISODIR/slint/liblouis-*.t?z \
	$ISODIR/slint/pcre2*.t?z \
	$ISODIR/slint/libsndfile*.t?z \
	$ISODIR/slint/orc-0*.t?z \
	$ISODIR/slint/flac*.t?z \
	$ISODIR/slint/libogg-*.t?z \
	$ISODIR/slint/libvorbis*.t?z \
	$ISODIR/slint/libyaml*.t?z \
	$ISODIR/slint/dbus-1*.t?z \
	$ISODIR/slint/kbd*.t?z \
	$ISODIR/slint/libnl3*.t?z \
	$ISODIR/slint/wireless_tools*.t?z \
	$ISODIR/slint/net-tools*.t?z \
	$ISODIR/slint/wpa_supplicant-nogui*.t?z \
	$ISODIR/slint/tar*.t?z \
	$ISODIR/slint/xz*.t?z \
	$ISODIR/slint/slang-*.t?z \
	$ISODIR/slint/most*.t?z \
	$ISODIR/slint/findutils*.t?z \
	$ISODIR/slint/ca-certificates*.t?z \
	$ISODIR/slint/openssl-solibs-*txz \
	$ISODIR/slint/libunistring*txz \
	$ISODIR/slint/nano*txz \
	$ISODIR/slint/swapinzram*txz \
	$ISODIR/slint/zstd*txz \
	$ISODIR/slint/util-linux*txz \
	$ISODIR/slint/json-c*txz \
	$ISODIR/slint/spkg*txz \
	$ISODIR/slint/slint-scripts*txz \
	$ISODIR/slint/gettext-0*txz \
	$ISODIR/slint/ncurses*txz \
	$ISODIR/slint/aaa_glibc-solibs-*.txz \
	$ISODIR/slint/efibootmgr*.txz \
	$ISODIR/slint/tree-1*.txz
    # "packages" includes packages only needed in the installer
	spkg -i --root "$DEST" "$ROOTDIR"/packages/*txz
	echo '#Empty file' > /"$DEST"/etc/asound.conf
	rm -r "$DEST"/usr/lib64/python*
	rm -r "$DEST"/usr/doc/*
	rm -r "$DEST"/usr/man/*
	rm "$DEST"/usr/bin/sndfile*
	rm "$DEST"/usr/bin/dbus-launch

	# 26/09/2022: removed bluez, bluez-firmware and liblouis and links (redundant with links-installer)
	# gettext-tools w3m (redundant with w3m-installer)
}  


customize() {
	chmod 755 "$DEST"/etc/rc.d/rc.espeakup
	chmod 755 "$DEST"/sbin/inst
	chmod 755 "$DEST"/etc/profile.d/alias.sh
	chmod 755 "$DEST"/sbin/alsa-info.sh
	chmod 755 "$DEST"/etc/rc.d/rc.alsa
	# We have included alsa-info.sh in the initrd. To update it:
	# wget --no-check-certificate -nv http://www.alsa-project.org/alsa-info.sh 2>/dev/null
	chmod 644 "$DEST"/usr/share/alsa/soundcards.conf
	chmod 644 "$DEST"/usr/share/alsa/utils.sh
}

localize_the_installer() {
	TEMPDIR="$(mktemp -d)" || exit 1
	export TEMPDIR
	# the script SeTlocales prevides the functions SeTCode and SeTLocaleDir
	# shellcheck disable=SC1090
	. "$SCRIPTS"/SeTlocales
	cd "$TEMPDIR" || exit 1
	# Copying new and modified files in $TMP/initrd/
	while read -r i; do
		[ ! "$i" ] && continue
		echo "$i included in the installer "
		mkdir -p "$DEST"/"$(dirname "$i")"
		cp -r "$SCRIPTS"/"$(basename "$i")" "$DEST"/"$(dirname "$i")"
		chmod 0755 "$DEST"/"$(dirname "$i")"/"$(basename "$i")"
	done < "$ROOTDIR"/files_in_the_initrd.list
	# Copying the documentation
	mkdir -p "$DEST"/usr/docinstaller
	cp "$ROOTDIR"/sources/doc/*html "$DEST"/usr/docinstaller
	cp "$ROOTDIR"/doc/doc "$DEST"/bin/
	chmod 0755 "$DEST"/bin/doc
	chmod 0644 "$DEST"/usr/docinstaller/*
	mkdir -p "$DEST"/usr/share/fonts
	cp "$ROOTDIR"/fonts/* "$DEST"/usr/share/fonts
	# /etc/rc.d/rc.espeakup calls speakup-restore shipped in the
	# slint-scripts
	# but we include this package in the installer...
	cp -a /usr/sbin/speakup-restore "$DEST"/sbin/
	# We need these programs to display translations
	# But we include gettext* in the installer...
	# cp -a /usr/bin/envsubst  "$DEST"/usr/bin/
	# cp -a /usr/bin/gettext*  "$DEST"/usr/bin/
	# we will include gconv-modules and all libraries in /usr/lib64/gconv
	# associated to encodings of PO files
    # We ship aaa_glibc-solibs in the installer, so...
	# mkdir -p "$DEST"/usr/lib64/gconv
	# for i in gconv-modules ISO8859-1.so ISO8859-15.so ISO8859-2.so KOI8-R.so; do
	# cp -a usr/lib64/gconv/"$i" "$DEST"/usr/lib64/gconv
    # glibc-i18n is too heavy to ship it in the intsaller, so...
	# Copying /usr/lib64/locale/<locale>/* and the (generated) MO files in: $TMP/initrd
	mkdir -p "$DEST"/usr/lib64/locale
	while read -r Locale; do
		ll=$(echo "$Locale"|cut -c 1-2)
		SeTCode
		SeTLocaleDir
		# Include the files gettext needs in /usr/lib64/locale.
		mkdir -p "$DEST"/usr/share/locale/"$LocaleDir"/LC_MESSAGES
		cp -r  /usr/lib64/locale/"$Locale" \
			"$DEST"/usr/lib64/locale
		if [ -f  /usr/share/locale/"$LocaleDir"/LC_MESSAGES/gettext-runtime.mo ]; then
			cp /usr/share/locale/"$LocaleDir"/LC_MESSAGES/gettext-runtime.mo \
			"$DEST"/usr/share/locale/"$LocaleDir"/LC_MESSAGES
		elif [ -f /usr/share/locale/"$ll"/LC_MESSAGES/gettext-runtime.mo ]; then
			cp /usr/share/locale/"$ll"/LC_MESSAGES/gettext-runtime.mo \
			"$DEST"/usr/share/locale/"$LocaleDir"/LC_MESSAGES
		fi
		if [ -f /usr/share/locale/"$LocaleDir"/LC_MESSAGES/dialog.mo ]; then
			cp /usr/share/locale/"$LocaleDir"/LC_MESSAGES/dialog.mo \
			"$DEST"/usr/share/locale/"$LocaleDir"/LC_MESSAGES
		elif [ -f /usr/share/locale/"$ll"/LC_MESSAGES/dialog.mo ]; then
			cp /usr/share/locale/"$ll"/LC_MESSAGES/dialog.mo \
			"$DEST"/usr/share/locale/"$LocaleDir"/LC_MESSAGES
		fi
		if [ -f  /usr/share/locale/"$LocaleDir"/LC_MESSAGES/util-linux.mo ]; then
			cp /usr/share/locale/"$LocaleDir"/LC_MESSAGES/util-linux.mo \
			"$DEST"/usr/share/locale/"$LocaleDir"/LC_MESSAGES
		elif [ -f /usr/share/locale/"$ll"/LC_MESSAGES/util-linux.mo ]; then
			cp /usr/share/locale/"$ll"/LC_MESSAGES/util-linux.mo \
			"$DEST"/usr/share/locale/"$LocaleDir"/LC_MESSAGES
		fi
		if [ -f  /usr/share/locale/"$LocaleDir"/LC_MESSAGES/nano.mo ]; then
			cp /usr/share/locale/"$LocaleDir"/LC_MESSAGES/nano.mo \
			"$DEST"/usr/share/locale/"$LocaleDir"/LC_MESSAGES
		elif [ -f /usr/share/locale/"$ll"/LC_MESSAGES/nano.mo ]; then
			cp /usr/share/locale/"$ll"/LC_MESSAGES/nano.mo \
			"$DEST"/usr/share/locale/"$LocaleDir"/LC_MESSAGES
		fi
	done < "$ROOTDIR"/doc/locales_list_sorted_by_name
	cd - || exit 1
}
create_initrd_Slint() {
	( cd "$DEST" || exit 1
	pwd
		rm -rf usr/lib/setup
		find . | cpio -o -H newc | xz -9fv -C crc32 > $ISODIR/initrd
	)
}

add_booting_equipment() {
# Put some docs at the root of the tree
echo "$ISOLABEL" > $ISODIR/slint/ISOLABEL
sed "s/<date>/$DATESTAMP/;s/+version+/slint64-${ISOVERSION}.iso/" "$ROOTDIR"/CONTENT.TXT > $ISODIR/CONTENT.TXT
sed "s/+version+/$SLINTVERSION/g" "$ROOTDIR"/doc/README.TXT > $ISODIR/README.TXT
echo "$DATESTAMP" > "$ISODIR"/DateBuilt
rm -rf "$ISODIR"/boot/grub
mkdir -p "$ISODIR/"boot/grub
cp "$ROOTDIR"/grub/grub.cfg $ISODIR/boot/grub/
#cp "$CWD"/grub/grub-mkrescue-sed.sh $ISODIR/boot/grub/
cd "$TEMPDIR" || exit 1
tar -xf $SLINTREPO/kernel-"$KVER"*txz boot/vmlinuz-"$KVER"
mv boot/vmlinuz-"$KVER" "$ISODIR"/linux
cd - || exit 1
(cd "$ISODIR" || exit 1
tree >> CONTENT.TXT)
}
#make_iso() {
#grub-mkrescue --locales='' --themes='' --compress=xz -V "$ISOLABEL" \
#-o $PATHTOISO -iso_mbr_part_type 0x83 -partition_offset 16 -J \
#--xorriso=./grub/grub-mkrescue-sed.sh $ISODIR
#}
make_iso() {
export MKRESCUE_SED_PARTNO=2
export MKRESCUE_SED_MODE=mjg
grub-mkrescue --locales='' --themes='' --compress=xz -V "$ISOLABEL" \
-o "$PATHTOISO" -iso_mbr_part_type 0x83 -partition_offset 16 -J \
--xorriso=grub-mkrescue-sed.sh "$ISODIR"
}
#make_iso_EFI() {
#MKRESCUE_SED_MODE="gpt_appended"
#grub-mkrescue --locales='' --themes='' --compress=xz -V "$ISOLABEL" \
#-o $PATHTOISO -iso_mbr_part_type 0x83 -partition_offset 16 -J \
#--xorriso=./grub/grub-mkrescue-sed.sh $ISODIR
#}
#
