#!/bin/sh -efu
#
# Copyright (C) 2024  Ajrat Makhmutov <rauty@altlinux.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.

alterator_api_version=1

. install2-sh-functions
. alterator-sh-functions
. install2-remount-functions

init_chroot()
{
    # check chroot state
    [ -s "$destdir/var/lib/rpm/Packages" ] && return 0

    # create apt/rpm skeleton directories
    mkdir -p -- "$destdir"
    cd "$destdir"
	mkdir -p -- \
	    ./dev \
	    ./proc \
	    ./sys \
	    ./etc/apt/{apt.conf,{sources,vendors}.list}.d \
	    ./run \
	    ./tmp \
	    ./var/cache/apt/archives/partial \
	    ./var/lib/apt/lists/partial \
	    ./var/lib/rpm >&2
    cd - >/dev/null

    # create a new rpm database
    rpmdb --initdb --dbpath "$destdir/var/lib/rpm"

    # create minimum device set
    cp -at "$destdir/dev" -- \
	/dev/null \
	/dev/zero \
	/dev/full \
	/dev/random \
	/dev/urandom \
	/dev/console \
	/dev/tty \
	/dev/ptmx

    # mount virtual filesystems
    if ! mount_chroot; then
        do_notify_error "Error mount virtual filesystem"
        return 1
    fi

    # add symlinks /var/run -> /run, and /var/lock -> /run/lock
    mkdir -p -- "$destdir/run/lock"
    ln -s ../run "$destdir/var/run"
    ln -s ../run/lock "$destdir/var/lock"

    # flag to notify installer's postinstall.d hooks about new system
    touch -- "$destdir/_NEW_SYSTEM_"

    apt-get update
}

export LANG=C

on_message()
{
	case "$in_action" in
	    write)
		local err=
		if ! err="$(init_chroot 2>&1)"; then
		    write_error "$err"
		fi
		;;
	esac
}

message_loop
