#!/bin/bash
# Copyright 2026 ANNE Media - https://anne.media
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# enter_chroot.sh -- enter the Slackware64 build chroot
# Usage: sudo ./enter_chroot.sh [-k]

# FIX: fail fast. The original set -e came *after* ./sync.sh, so a
#      failed sync (e.g. missing packages) was ignored and we'd drop
#      into a chroot with an empty/stale repo/source/z.
set -e
[ "$(id -u)" -eq 0 ] || { echo "Run with: sudo $0" >&2; exit 1; }


# Locate this script's directory early so we can source the shared
# blacklist. BUILD_DIR is reused further down to locate sync.sh.
BUILD_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
BLACKLIST_SH="$BUILD_DIR/blacklist.sh"
[ -f "$BLACKLIST_SH" ] \
    || { echo "ERROR: blacklist.sh not found at $BLACKLIST_SH" >&2; exit 1; }
# shellcheck source=blacklist.sh
. "$BLACKLIST_SH"

CHROOT_DIR="$(cd -- "$BUILD_DIR/../.." && pwd -P)"
chown -R annestar:root $CHROOT_DIR/repo/

# ----------------------------------------------------------------------
# SERVICE ACCOUNTS
# SlackBuilds for daemons (tor, privoxy, squid, ...) bail out at
# build time if their service user/group does not exist. The chroot has
# its own /etc/passwd and /etc/group, so they must be created *inside*
# the chroot -- the host's accounts do not carry in.
#
# Format: name:uid:gid:comment:home:shell
# UIDs/GIDs are the ones reserved by slackbuilds.org:
#   https://slackbuilds.org/uid_gid.txt
# Add entries as needed. The block is idempotent -- rerunning is safe.
# ----------------------------------------------------------------------
SERVICE_ACCOUNTS=(
    "tor:220:220:The Onion Router:/dev/null:/bin/false"
    # "privoxy:206:206:Privoxy:/dev/null:/bin/false"
    # "squid:209:209:Squid cache:/var/cache/squid:/bin/false"
    # "lighttpd:208:208:Lighttpd:/var/www:/bin/false"
    # "nagios:213:213:Nagios:/dev/null:/bin/false"
)

# is_blacklisted() and BLACKLIST_PATTERNS come from blacklist.sh,
# sourced above. The inner chroot bash re-implements is_blacklisted
# inline further down (it runs inside the chroot and cannot source
# blacklist.sh from there); it expands "${BLACKLIST_PATTERNS[@]}" from
# this outer shell, so both stay in sync via the shared file.

# overriding -k, set to 0 if no kernel install is wanted
KERNEL_FLAG=1
while getopts "k" opt; do
    case $opt in
        k) KERNEL_FLAG=1 ;;
        *) echo "Usage: $0 [-k]"; exit 1 ;;
    esac
done


# rsync -avz --delete --progress --exclude '/testing' \
# rsync://mirror.slackbuilds.org/slackware/slackware64-current/ "$CHROOT_DIR/repo/"
# rsync -avz --delete --progress rsync://mirror.slackbuilds.org/slackware/slackware64-current/ "$CHROOT_DIR/repo/"

SYNC_SH="$BUILD_DIR/sync.sh"
[ -x "$SYNC_SH" ] || { echo "ERROR: sync.sh not found or not executable at $SYNC_SH"; exit 1; }

echo ">>> Running $SYNC_SH ..."
"$SYNC_SH"


REPO_DIR="$CHROOT_DIR/repo/slackware64"
export PATH="/sbin:/usr/sbin:$PATH"

[ -d "$CHROOT_DIR" ] || { echo "ERROR: chroot dir not found"; exit 1; }
if [ ! -d "$REPO_DIR/a" ]; then
    echo "ERROR: 64-bit mirror not found at $REPO_DIR"
    exit 1
fi

if mount | grep -q " $CHROOT_DIR/"; then
    echo ">>> Active bind mounts under $CHROOT_DIR; skipping chown."
    echo "    Run exit_chroot.sh first, or unmount manually:"
    mount | grep " $CHROOT_DIR"
else
    chown -R annestar:root "$CHROOT_DIR"
fi

mkdir -p "$CHROOT_DIR"/{proc,sys,dev,dev/pts}

# ---- Bootstrap (if no bash exists) ----
if [ ! -x "$CHROOT_DIR/bin/bash" ]; then
    echo ">>> Installing base system (blacklisted packages excluded)..."
    for series in a ap d l n x xap xfce y kde t tcl e f k; do
        series_dir="$REPO_DIR/$series"
        [ -d "$series_dir" ] || continue
        pkgs=()
        for pkg in "$series_dir"/*.t?z; do
            [ -f "$pkg" ] || continue
            pkgname=$(basename "$pkg")
            is_blacklisted "$pkgname" || pkgs+=("$pkg")
        done
        [ ${#pkgs[@]} -gt 0 ] && ROOT="$CHROOT_DIR" installpkg "${pkgs[@]}"
    done
    # remaining series
    for series_dir in "$REPO_DIR"/*/; do
        series=$(basename "$series_dir")
        [[ " a ap d l n x xap xfce y kde t tcl e f k " =~ " $series " ]] && continue
        [ "$series" = "kernels" ] && continue
        pkgs=()
        for pkg in "$series_dir"/*.t?z; do
            [ -f "$pkg" ] || continue
            pkgname=$(basename "$pkg")
            is_blacklisted "$pkgname" || pkgs+=("$pkg")
        done
        [ ${#pkgs[@]} -gt 0 ] && ROOT="$CHROOT_DIR" installpkg "${pkgs[@]}"
    done
    touch "$CHROOT_DIR/tmp/.initial_install"
    echo ">>> Bootstrap complete (blacklist applied)."
fi
# ---- Mount virtual filesystems ----
mountpoint -q "$CHROOT_DIR/proc" || mount --bind /proc "$CHROOT_DIR/proc"
mountpoint -q "$CHROOT_DIR/sys"  || mount --bind /sys  "$CHROOT_DIR/sys"
mountpoint -q "$CHROOT_DIR/dev"  || mount --bind /dev  "$CHROOT_DIR/dev"
mountpoint -q "$CHROOT_DIR/dev/pts" || mount --bind /dev/pts "$CHROOT_DIR/dev/pts"
cp /etc/resolv.conf "$CHROOT_DIR/etc/resolv.conf"

# ---- Ensure service accounts exist inside the chroot ----
# Runs every time and is idempotent: groupadd/useradd are guarded by
# greps against the chroot's own /etc/{group,passwd}. Uses --root so we
# do not need a fully working chroot (no /proc required) and so no
# mountpoint is needed inside. If the chroot has no bash yet (e.g. a
# brand-new tree that bootstrap just populated), chroot still works
# because we are only running user/group tools, not bash.
if [ -x "$CHROOT_DIR/usr/sbin/groupadd" ] && [ -x "$CHROOT_DIR/usr/sbin/useradd" ]; then
    echo ">>> Ensuring service accounts exist..."
    for entry in "${SERVICE_ACCOUNTS[@]}"; do
        IFS=':' read -r name uid gid comment home shell <<< "$entry"

        if ! grep -q "^${name}:" "$CHROOT_DIR/etc/group"; then
            chroot "$CHROOT_DIR" /usr/sbin/groupadd -g "$gid" "$name" \
                && echo "    + group  ${name} (gid ${gid})"
        fi

        if ! grep -q "^${name}:" "$CHROOT_DIR/etc/passwd"; then
            chroot "$CHROOT_DIR" /usr/sbin/useradd \
                -u "$uid" -g "$gid" -c "$comment" -d "$home" -s "$shell" "$name" \
                && echo "    + user   ${name} (uid ${uid}, gid ${gid})"
        fi
    done
else
    echo ">>> Skipping service accounts: groupadd/useradd not present in chroot."
fi

# ---- Upgrade phase ----
if [ -x "$CHROOT_DIR/bin/bash" ]; then
    echo ">>> Upgrading packages (blacklist still enforced)..."
    chroot "$CHROOT_DIR" /bin/bash -c "
        KERNEL_FLAG='$KERNEL_FLAG'
        export PATH=\"/sbin:/usr/sbin:/bin:/usr/bin\"

        is_blacklisted() {
            local pkg=\"\$1\"
            for pat in $(printf '%s ' "${BLACKLIST_PATTERNS[@]}"); do
                if [[ \"\$pkg\" =~ \$pat ]]; then
                    [[ \"\$pkg\" =~ compat ]] && return 1 || return 0
                fi
            done
            return 1
        }

        LOG=/tmp/upgradepkg.log
        : > \"\$LOG\"

        changed=0
        current=0
        failed=0

        for series_dir in /repo/slackware64/*/; do
            [ -d \"\$series_dir\" ] || continue
            for pkg in \"\$series_dir\"/*.t?z; do
                [ -f \"\$pkg\" ] || continue
                pkgname=\$(basename \"\$pkg\")

                if [ \"\$KERNEL_FLAG\" -eq 0 ] && [[ \"\$pkgname\" == kernel-* ]]; then
                    continue
                fi
                is_blacklisted \"\$pkgname\" && continue

                # Already installed at this exact version? Skip silently.
                pkgbase=\"\${pkgname%.t?z}\"
                if [ -f \"/var/log/packages/\$pkgbase\" ]; then
                    current=\$((current + 1))
                    continue
                fi

                # New install or version change. Do it, print one line.
                if upgradepkg --install-new \"\$pkg\" >> \"\$LOG\" 2>&1; then
                    printf '  + %s\n' \"\$pkgname\"
                    changed=\$((changed + 1))
                else
                    printf '  ! %s (see %s)\n' \"\$pkgname\" \"\$LOG\"
                    failed=\$((failed + 1))
                fi
            done
        done

        printf '  %d installed/upgraded, %d already current, %d failed\n' \
            \"\$changed\" \"\$current\" \"\$failed\"

        [ \"\$failed\" -eq 0 ]
    "
    echo ">>> Upgrade finished."
fi

# ---- Prune packages not in packages.list or source/z ----
if [ ! -f "$CHROOT_DIR/repo/packages.list" ]; then
    echo "WARNING: $CHROOT_DIR/repo/packages.list not found, skipping pruning."
else
    echo ">>> Pruning packages not listed in /repo/packages.list or /repo/source/z..."
    chroot "$CHROOT_DIR" /bin/bash <<'PRUNE_EOF'
declare -A allowed

# 1. packages.list (CRLF-safe, comment-safe, whitespace-safe)
while IFS= read -r raw || [ -n "$raw" ]; do
    raw="${raw%$'\r'}"
    line="${raw%%#*}"
    line="${line#"${line%%[![:space:]]*}"}"
    line="${line%"${line##*[![:space:]]}"}"
    [ -n "$line" ] && allowed["$line"]=1
done < /repo/packages.list

# 2. Each subdirectory of /repo/source/z is a package name
if [ -d /repo/source/z ]; then
    for d in /repo/source/z/*/; do
        [ -d "$d" ] || continue
        allowed["$(basename "$d")"]=1
    done
    # also catch any loose .t?z sitting directly in z/
    for f in /repo/source/z/*.t?z; do
        [ -f "$f" ] || continue
        base=$(basename "$f"); base="${base%.t?z}"
        base=$(echo "$base" | sed 's/-[^-]*-[^-]*-[^-]*$//')
        [ -n "$base" ] && allowed["$base"]=1
    done
fi

# 3. Only prune if z's were actually populated
if [ -d /repo/source/z ] && [ -n "$(ls -A /repo/source/z 2>/dev/null)" ]; then
    for pkgfile in /var/log/packages/*; do
        [ -f "$pkgfile" ] || continue
        base=$(basename "$pkgfile" | sed 's/-[^-]*-[^-]*-[^-]*$//')
        if [ -z "${allowed[$base]}" ]; then
            echo "Removing $base"
            removepkg "$base"
        fi
    done
else
    echo "!!! /repo/source/z is empty -- skipping prune."
fi

exit 0
PRUNE_EOF
    echo ">>> Pruning finished."
fi

# ---- Configure gpg for keyboxd-free operation ----
mkdir -p "$CHROOT_DIR/root/.gnupg"
chmod 700 "$CHROOT_DIR/root/.gnupg"

if [ -f "$CHROOT_DIR/root/.gnupg/common.conf" ]; then
    sed -i 's/^use-keyboxd/#use-keyboxd/' \
        "$CHROOT_DIR/root/.gnupg/common.conf"
else
    : > "$CHROOT_DIR/root/.gnupg/common.conf"
fi


# ---- Refresh override .upstream snapshots from the source tree ----
# For every <name>.SlackBuild under $CHROOT_DIR/repo/overrides/, copy the
# matching upstream file from $CHROOT_DIR/repo/source/ into
# <name>.SlackBuild.upstream next to the override. This keeps the
# diff target current with the mirror instead of frozen at the moment
# the override was first written. build_world.sh's own stash logic
# ("stash only if .upstream missing") will then leave it alone.
#
# Files in the override directory itself are NOT touched -- only their
# .upstream companions. The override still wins at build time.
OVERRIDES_DIR="$CHROOT_DIR/repo/overrides"
SOURCE_TREE="$CHROOT_DIR/repo/source"

if [ -d "$OVERRIDES_DIR" ] && [ -d "$SOURCE_TREE" ]; then
    echo ">>> Refreshing override .upstream snapshots from $SOURCE_TREE ..."
    refreshed=0
    missing=0
    while IFS= read -r -d '' ob; do
        rel="${ob#$OVERRIDES_DIR/}"
        src="$SOURCE_TREE/$rel"
        if [ ! -f "$src" ]; then
            echo "!!! No source counterpart for override: $rel (skipping)"
            missing=$((missing + 1))
            continue
        fi
        cp -a "$src" "$ob.upstream"
        echo ">>>   refreshed: ${rel}.upstream"
        refreshed=$((refreshed + 1))
    done < <(find "$OVERRIDES_DIR" -name '*.SlackBuild' -type f -print0)
    echo ">>>   refreshed $refreshed snapshot(s), $missing without source counterpart"
else
    echo ">>> No overrides to refresh ($OVERRIDES_DIR or $SOURCE_TREE missing)"
fi

unset CFLAGS CXXFLAGS SLKCFLAGS SLKLDFLAGS CPPFLAGS LDFLAGS MAKEFLAGS

echo "Entering chroot..."
exec chroot "$CHROOT_DIR" /bin/bash -l