#!/usr/bin/bash
set -Eeuo pipefail

target_root="${1:-}"

if [ -z "$target_root" ] || [ "$target_root" = "/" ]; then
    echo "Invalid Calamares target root: ${target_root:-empty}" >&2
    exit 1
fi

archive="${TUXENIX_ROOTFS_IMAGE:-/run/iso/live/tuxenix-rootfs.tar.zst}"
install_log="${TUXENIX_INSTALL_LOG:-/var/log/tuxenix-calamares-install.log}"
failed_stage="initial validation"

mkdir -p "$(dirname "$install_log")"
touch "$install_log"
chmod 0600 "$install_log"
if [ "${TUXENIX_INSTALL_LOG_ACTIVE:-0}" != 1 ]; then
    exec 3>&1 4>&2
    exec >>"$install_log" 2>&1
fi

visible_info() {
    printf '%s\n' "$*"
    printf '%s\n' "$*" >&3
}

visible_error() {
    printf '%s\n' "$*" >&2
    printf '%s\n' "$*" >&4
}

report_failure() {
    status="$1"
    line="$2"
    command="$3"
    trap - ERR
    visible_error "Tuxenix rootfs setup failed during: $failed_stage"
    visible_error "Exit status $status at helper line $line: $command"
    visible_error "Detailed installer log: $install_log"
    echo "Recent installer log output:" >&4
    tail -n 30 "$install_log" >&4 2>/dev/null || true
    exit "$status"
}
trap 'status=$?; report_failure "$status" "$LINENO" "$BASH_COMMAND"' ERR

if [ ! -f "$archive" ]; then
    visible_error "Tuxenix rootfs image is missing: $archive"
    exit 1
fi

ensure_line() {
    file="$1"
    pattern="$2"
    line="$3"

    touch "$file"
    if ! grep -Eq "$pattern" "$file"; then
        printf '%s\n' "$line" >> "$file"
    fi
}

ensure_target_account() {
    mkdir -p "$target_root/etc" "$target_root/var/lib/dbus"
    ensure_line "$target_root/etc/group" '^messagebus:' \
        'messagebus:x:18:'
    ensure_line "$target_root/etc/passwd" '^messagebus:' \
        'messagebus:x:18:18:System Message Bus:/run/dbus:/bin/false'
    ln -snf /etc/machine-id "$target_root/var/lib/dbus/machine-id"
    chmod 755 "$target_root/var/lib/dbus"
}

ensure_login_target() {
    if [ ! -x "$target_root/usr/sbin/dinit" ]; then
        visible_error "Installed root is missing dinit."
        exit 1
    fi

    rm -f "$target_root/usr/sbin/init"
    ln -snf dinit "$target_root/usr/sbin/init"
}

ensure_runtime_layout() {
    install -d -o 0 -g 0 -m 0755 "$target_root/var/log"

    if [ -d "$target_root/usr/lib/modules" ] && [ ! -e "$target_root/lib/modules" ]; then
        mkdir -p "$target_root/lib"
        ln -snf ../usr/lib/modules "$target_root/lib/modules"
    fi

    mkdir -p "$target_root/etc/profile.d"
    cat > "$target_root/etc/profile.d/00-tuxenix-path.sh" <<'EOF'
# Make base admin tools available in text logins.
case ":$PATH:" in
    *:/usr/sbin:*) ;;
    *) PATH="/usr/sbin:$PATH" ;;
esac
case ":$PATH:" in
    *:/sbin:*) ;;
    *) PATH="/sbin:$PATH" ;;
esac
export PATH
EOF
    chmod 644 "$target_root/etc/profile.d/00-tuxenix-path.sh"

    cat > "$target_root/etc/resolv.conf" <<'EOF'
nameserver 1.1.1.1
nameserver 8.8.8.8
EOF
    chmod 644 "$target_root/etc/resolv.conf"
}

preserve_network_connections() {
    source_connections="${TUXENIX_LIVE_CONNECTIONS_DIR:-/etc/NetworkManager/system-connections}"
    target_connections="$target_root/etc/NetworkManager/system-connections"
    copied=0

    # Numeric ownership avoids NSS lookups in the intentionally small live
    # environment, where symbolic accounts may not have been initialized yet.
    install -d -o 0 -g 0 -m 0700 "$target_connections"
    if [ ! -d "$source_connections" ]; then
        return
    fi

    for profile in "$source_connections"/*.nmconnection; do
        if [ ! -f "$profile" ]; then
            continue
        fi
        install -o 0 -g 0 -m 0600 \
            "$profile" "$target_connections/$(basename "$profile")"
        copied=$((copied + 1))
    done

    if [ "$copied" -gt 0 ]; then
        echo "Preserved $copied NetworkManager connection profile(s)."
    fi
}

visible_info "Copying Tuxenix root filesystem image into $target_root"
visible_info "archive: $archive"
echo
echo "tools:"
command -v tar
command -v zstd
tar --version | head -1 || true
zstd --version || true
echo
echo "space:"
df -h "$target_root" "$(dirname "$archive")" /tmp 2>/dev/null || true
echo
ls -lh "$archive"
echo
visible_info "Testing compressed image..."
failed_stage="compressed root filesystem validation"
zstd -t "$archive"
visible_info "Extracting image..."
failed_stage="root filesystem extraction"
zstd -dc "$archive" | tar -xpf - -C "$target_root" --numeric-owner --delay-directory-restore
failed_stage="target account setup"
ensure_target_account
failed_stage="dinit login target setup"
ensure_login_target
failed_stage="target runtime layout setup"
ensure_runtime_layout
failed_stage="target timezone data setup"
/usr/libexec/tuxenix-calamares-timezone-data.py "$target_root"
failed_stage="NetworkManager connection preservation"
preserve_network_connections
trap - ERR
visible_info "Image copy complete."
