DistroHopper/dh

873 lines
32 KiB
Bash
Executable file

#!/usr/bin/env bash
function wayland_check() {
if [ -n "$XDG_SESSION_ID" ]; then
session_type=$(loginctl show-session "$XDG_SESSION_ID" -p Type 2>$DH_NULL | cut -d= -f2)
else
session_type=""
fi
case "$session_type" in
wayland)
export GDK_BACKEND=x11
echo "Running on Wayland"
;;
x11)
echo "Running on X"
;;
"")
echo "Running on TTY"
;;
*)
echo "Not sure where I am running"
;;
esac
}
SCRIPT_DIR="${APPDIR:-$(dirname "$(realpath "$0")")}"
# Get OS description from template files
# For ready VMs (e.g. "ubuntu-24.04"), progressively strips release suffix
# to find the matching template ("ubuntu"). Falls back to empty string.
get_os_description() {
local name="$1" candidate
# Try exact match first (for supported VMs where name == OS name)
if [ -f "${SCRIPT_DIR}/templates/${name}" ]; then
OS="$name" bash -c "source '${SCRIPT_DIR}/templates/${name}' >$DH_NULL 2>$DH_NULL; echo \$DESCRIPTION" 2>$DH_NULL
return
fi
# Progressive strip for ready VMs (e.g. "ubuntu-budgie-24.04" → "ubuntu")
candidate="$name"
while [ -n "$candidate" ]; do
next="${candidate%-*}"
[ "$next" = "$candidate" ] && break
candidate="$next"
if [ -f "${SCRIPT_DIR}/templates/${candidate}" ]; then
OS="$candidate" bash -c "source '${SCRIPT_DIR}/templates/${candidate}' >$DH_NULL 2>$DH_NULL; echo \$DESCRIPTION" 2>$DH_NULL
return
fi
done
# Last chance: whatever candidate remains (handles no-hyphen names).
if [ -n "$candidate" ] && [ -f "${SCRIPT_DIR}/templates/${candidate}" ]; then
OS="$candidate" bash -c "source '${SCRIPT_DIR}/templates/${candidate}' >$DH_NULL 2>$DH_NULL; echo \$DESCRIPTION" 2>$DH_NULL
return
fi
echo ""
}
root=""
function root_check() {
if [ "$(id -u)" != 0 ]; then
if [ -f /usr/bin/sudo ]; then
echo "$(tput bold)INFO: Using sudo for root operations.$(tput sgr0)"
root="sudo"
elif [ -f /usr/bin/doas ]; then
echo "$(tput bold)INFO: Using doas for root operations.$(tput sgr0)"
root="doas"
fi
fi
}
function set_variables() {
# DEBUG mod
#bash -x ./dh 2>&1 | tee output.log
#progname="${progname:="${0##*/}"}"
progname="DistroHopper"
export GDK_CORE_DEVICE_EVENTS=1
version="0.93"
#GTK_THEME="alt-dialog"
DH_CONFIG_DIR="${HOME}/.config/dh"
DH_CONFIG="${DH_CONFIG_DIR}/config"
DH_ICON_DIR="${DH_CONFIG_DIR}/icons"
if [[ -n "${APPDIR:-}" ]]; then
PATH_PREFIX="${APPDIR}/bin/"
else
PATH_PREFIX="/usr/bin/"
fi
TMP_DIR="/tmp"
# The terminal emulator the desktop entry opens. "true" means no
# terminal, which is the safe default: an entry naming a terminal that
# is not installed does not start.
terminal="false"
# shellcheck disable=SC2089
replace='"!"'
VMS_DIR="${HOME}/vm"
RAMDISK="no"
RAMDISK_DIR="/dev/shm/quickemu"
ISO_DIR=""
USE_TEMPLATES="no"
if [ -f "${DH_CONFIG}" ]; then
# shellcheck source=/dev/null
. "${DH_CONFIG}"
fi
[ -n "${VMS_DIR}" ] || VMS_DIR="${HOME}/vm"
[ -n "${RAMDISK}" ] || RAMDISK="no"
[ -n "${RAMDISK_DIR}" ] || RAMDISK_DIR="/dev/shm/quickemu"
[ -n "${USE_TEMPLATES}" ] || USE_TEMPLATES="no"
# Fall back to templates when the (generated) public/ metadata is absent,
# e.g. in a source/AppImage checkout that only ships templates/.
if [ "${USE_TEMPLATES}" != "yes" ] && [ ! -d "${SCRIPT_DIR}/public" ] && [ -d "${SCRIPT_DIR}/templates" ]; then
USE_TEMPLATES="yes"
fi
[ -n "${terminal}" ] || terminal="true"
if [ "${USE_TEMPLATES}" == "yes" ]; then
export DH_USE_TEMPLATES="yes"
export DH_USER_TEMPLATES="yes"
else
unset DH_USER_TEMPLATES
fi
# shellcheck disable=SC2090
# Keep the per-user icon cache in sync with the shipped icons.
mkdir -p "${DH_ICON_DIR}" 2>/dev/null || true
if [ -d "${SCRIPT_DIR}/icons" ]; then
cp -f "${SCRIPT_DIR}/icons"/* "${DH_ICON_DIR}/" 2>/dev/null || true
fi
# App icon lives in website-source in the repo; ensure it is cached too.
if [ ! -f "${DH_ICON_DIR}/hop.png" ]; then
for _hop in "${SCRIPT_DIR}/website-source/hop220.png" "${SCRIPT_DIR}/icons/hop.png" /usr/share/distrohopper/icons/hop.png; do
if [ -f "${_hop}" ]; then
cp -f "${_hop}" "${DH_ICON_DIR}/hop.png" 2>/dev/null || true
break
fi
done
fi
export DH_CONFIG_DIR DH_CONFIG replace DH_ICON_DIR PATH_PREFIX TMP_DIR terminal VMS_DIR RAMDISK RAMDISK_DIR ISO_DIR USE_TEMPLATES
#check_and_set_mode
# Set traps to catch the signals and exit gracefully
trap "exit" INT
}
# installation ---------------------------------------------------------
function dependencies_check_gui() {
[ -f "${PATH_PREFIX}/yad" ] || echo "Yad not installed!"
}
function install_needed_apt() {
$root apt install qemu bash coreutils ovmf grep jq lsb procps python3 genisoimage usbutils util-linux sed spice-client-gtk swtpm wget xdg-user-dirs zsync unzip yad
}
function install_needed_pacman() {
$root pacman -S cdrtools coreutils edk2-ovmf grep jq procps python3 qemu-full sed socat spice-gtk swtpm usbutils util-linux wget xdg-user-dirs xorg-xrandr zsync getext yad
}
function install_needed_xbps() {
$root xbps-install -S qemu bash coreutils grep jq procps-ng python3 util-linux sed spice-gtk swtpm usbutils wget xdg-user-dirs xrandr unzip zsync socat yad
}
function install_needed_dnf() {
$root dnf install qemu bash coreutils edk2-tools grep jq lsb procps python3 genisoimage usbutils util-linux sed spice-gtk-tools swtpm wget xdg-user-dirs xrandr unzip yad
}
function install_dependencies() {
# Find the current distribution and install dependecies
if [ -f /etc/os-release ]; then
if [ -f "${PATH_PREFIX}/pacman" ]; then
install_needed_pacman
elif [ -f "${PATH_PREFIX}/apt" ]; then
install_needed_apt
elif [ -f "${PATH_PREFIX}/xbps-install" ]; then
install_needed_xbps
elif [ -f "${PATH_PREFIX}/dnf" ]; then
install_needed_dnf
else
echo "Error unknown distro!"
#exit 1
fi
fi
}
function create_dirs() {
mkdir -p "${DH_CONFIG_DIR}"
touch "${DH_CONFIG}"
mkdir -p "${DH_ICON_DIR}"
mkdir -p "${DH_CONFIG_DIR}/supported"
mkdir -p "${DH_CONFIG_DIR}/ready"
}
function save_config() {
local temp_config
mkdir -p "${DH_CONFIG_DIR}" || return 1
temp_config=$(mktemp "${DH_CONFIG}.XXXXXX") || return 1
{
printf 'VMS_DIR=%q\nexport VMS_DIR\n' "${VMS_DIR}"
printf 'RAMDISK=%q\nexport RAMDISK\n' "${RAMDISK}"
printf 'RAMDISK_DIR=%q\nexport RAMDISK_DIR\n' "${RAMDISK_DIR}"
printf 'ISO_DIR=%q\nexport ISO_DIR\n' "${ISO_DIR}"
printf 'USE_TEMPLATES=%q\nexport USE_TEMPLATES\n' "${USE_TEMPLATES}"
} >"${temp_config}" || {
rm -f "${temp_config}"
return 1
}
mv -f "${temp_config}" "${DH_CONFIG}"
echo "Config saved: ${DH_CONFIG}"
}
function choose_vms_dir() {
local new_dir
new_dir="$(yad --width=900 --height=900 --file --directory \
--title="Where to save VMs?" --filename="${VMS_DIR}")" || return 1
[ -n "${new_dir}" ] || return 1
VMS_DIR="${new_dir}"
export VMS_DIR
save_config
echo "VMs directory set to: ${VMS_DIR}"
}
function set_vms_directory() {
echo "[dh] Set VMs directory..."
local old_dir="${VMS_DIR}"
choose_vms_dir || return
[ "${VMS_DIR}" == "${old_dir}" ] && return
renew_ready_vms
renew_supported_vms
}
function set_ramdisk() {
echo "[dh] RAM disk..."
local output enabled ramdisk_dir
output="$(yad --title="RAM disk" --form --separator=$'\t' \
--field="Create VM disk in RAM (tmpfs)":CHK \
--field="RAM disk directory":DIR \
"$([ "${RAMDISK}" == "yes" ] && echo TRUE || echo FALSE)" "${RAMDISK_DIR}")" || return 1
enabled="${output%%$'\t'*}"
ramdisk_dir="${output#*$'\t'}"
[ "${output}" != "${enabled}" ] || return 1
case "${enabled}" in
TRUE) RAMDISK="yes" ;;
FALSE) RAMDISK="no" ;;
*) return 1 ;;
esac
[ -n "${ramdisk_dir}" ] || return 1
RAMDISK_DIR="${ramdisk_dir}"
export RAMDISK RAMDISK_DIR
save_config || return 1
echo "RAM disk: ${RAMDISK} (${RAMDISK_DIR})"
yad --title="RAM disk" --width=400 \
--text="$([ "${RAMDISK}" == "yes" ] && echo "RAM disk enabled: ${RAMDISK_DIR}" || echo "RAM disk disabled")"
}
DH_VERSION_FILE=""
function install_dh() {
if [[ -n "${APPDIR:-}" ]]; then
echo "Running from AppImage: installation is not required."
return 0
fi
DH_VERSION_FILE="${DH_CONFIG_DIR}/version"
local install_type="fresh"
if [ -f "${DH_VERSION_FILE}" ]; then
local old_version
old_version=$(cat "${DH_VERSION_FILE}")
if [ "${old_version}" != "${version}" ]; then
install_type="upgrade"
echo "Upgrading DistroHopper ${old_version} → ${version}"
else
install_type="reinstall"
echo "DistroHopper ${version} already installed"
fi
else
echo "Installing DistroHopper ${version}"
fi
cp -f "${SCRIPT_DIR}"/{generate,qget,q,dh,quickemu,quickreport,chunkcheck,lib.sh} "${PATH_PREFIX}" >$DH_NULL 2>$DH_NULL || \
$root cp -f "${SCRIPT_DIR}"/{generate,qget,q,dh,quickemu,quickreport,chunkcheck,lib.sh} "${PATH_PREFIX}"
cp -f "${SCRIPT_DIR}"/dh-refresh "${PATH_PREFIX}" >$DH_NULL 2>$DH_NULL || \
$root cp -f "${SCRIPT_DIR}"/dh-refresh "${PATH_PREFIX}"
mkdir -p "${PATH_PREFIX}/public" "${PATH_PREFIX}/templates" >$DH_NULL 2>$DH_NULL || $root mkdir -p "${PATH_PREFIX}/public" "${PATH_PREFIX}/templates"
cp -f "${SCRIPT_DIR}"/public/* "${PATH_PREFIX}/public/" >$DH_NULL 2>$DH_NULL || $root cp -f "${SCRIPT_DIR}"/public/* "${PATH_PREFIX}/public/"
cp -f "${SCRIPT_DIR}"/templates/* "${PATH_PREFIX}/templates/" >$DH_NULL 2>$DH_NULL || $root cp -f "${SCRIPT_DIR}"/templates/* "${PATH_PREFIX}/templates/"
if [ -d "${SCRIPT_DIR}/icons" ]; then
cp -f "${SCRIPT_DIR}"/icons/* "${DH_ICON_DIR}/" >$DH_NULL 2>$DH_NULL || $root cp -f "${SCRIPT_DIR}"/icons/* "${DH_ICON_DIR}/"
fi
mkdir -p "${DH_CONFIG_DIR}/ready"
mkdir -p "${DH_CONFIG_DIR}/supported"
echo "${version}" > "${DH_VERSION_FILE}"
}
# shellcheck disable=SC2154
# Escape one desktop Exec argument (key-file escaping followed by argv quoting).
function desktop_quote_argument() {
local quoted="$1"
quoted="${quoted//\\/\\\\\\\\}"
quoted="${quoted//\"/\\\\\"}"
quoted="${quoted//\$/\\\\$}"
quoted="${quoted//\`/\\\\\`}"
quoted="${quoted//%/%%}"
printf '\"%s\"' "$quoted"
}
function create_desktop_entry() {
# YAD reloads on CREATED/DELETED, not CHANGED. Publishing an empty
# .desktop file before writing it races the monitor, especially when
# there is only one ready VM and no later creation triggers a rescan.
# Stage in the same directory (without a .desktop suffix), then rename
# the complete, executable entry into place atomically.
local desktop_tmp
desktop_tmp=$(mktemp "${DESKTOP_FILE%/*}/.dh-entry.XXXXXX") || return 1
if ! cat <<EOF > "${desktop_tmp}"
[Desktop Entry]
Version=${version}
Type=${type}
Name=${name}
GenericName=${gname}
Comment=${comment}
Exec=${execmd}
Icon=${icon}
Terminal=${terminal}
X-MultipleArgs=${args}
Type=${type}
Categories=${categories}
StartupNotify=${notify}
MimeType=${mime}
Keywords=${keyword}
EOF
then
rm -f "${desktop_tmp}"
return 1
fi
if ! chmod +x "${desktop_tmp}" || ! mv -f "${desktop_tmp}" "${DESKTOP_FILE}"; then
rm -f "${desktop_tmp}"
return 1
fi
}
# shellcheck disable=SC2269
function desktop_entry_dh() {
DESKTOP_FILE="${TMP_DIR}/dh.desktop"
type='Application'
name='DistroHopper'
comment='Quickly download, create and run VM of any operating system.'
version="${version}"
execmd="sh -c 'cd ${VMS_DIR} && dh'"
icon="${DH_ICON_DIR}/hop.png"
categories='System;X-Virtualization;'
export -f create_desktop_entry
create_desktop_entry
$root cp "${TMP_DIR}/dh.desktop" /usr/share/applications/
}
function installation_process() {
dependencies_check_gui
install_dependencies
create_dirs
choose_vms_dir
install_dh
desktop_entry_dh
}
# basic ----------------------------------------------------------------
run_in_terminal() {
if [ -t 1 ] || [ "${DH_DEBUG:-}" = "1" ]; then
interminal="yes"
else
interminal="no"
fi
}
# shellcheck disable=SC2269
function renew_ready_vms() {
echo "[dh] Renew ready..."
# YAD field actions run in separate bash processes, so reload persisted
# settings to pick up a VM directory chosen after the GUI was opened.
if [ -f "${DH_CONFIG}" ]; then
# shellcheck source=/dev/null
. "${DH_CONFIG}"
fi
# The VMs are read from VMS_DIR, but the working directory is restored
# afterwards: a later relative path (e.g. ./qget) would otherwise be
# resolved inside the VMs directory.
local _old_dir="${PWD}"
cd "${VMS_DIR}" || { echo "ERROR: VMS_DIR not set!"; exit 1; }
rm -f "${DH_CONFIG_DIR}/ready"/*.desktop >$DH_NULL 2>$DH_NULL
mkdir -p "${DH_CONFIG_DIR}/ready"
for vm_conf in *.conf; do
[ -f "${vm_conf}" ] || continue
[ "${vm_conf}" = "distrohopper.conf" ] && continue
VMname=$(basename "${VMS_DIR}/${vm_conf}" .conf)
echo "${VMname}.desktop"
# Use fuzzy matching to find the best matching icon file (ready to run VMs)
icon_name=$(basename "${VMS_DIR}/${vm_conf}" .conf | cut -d'-' -f -2)
icon_file=$(find "${DH_ICON_DIR}" -type f -iname "${icon_name// /}.*" | head -n 1)
# If no icon was found, try shorter name (ready to run VMs)
if [ -z "${icon_file}" ]; then
icon_name=$(basename "${VMS_DIR}/${vm_conf}" .conf | cut -d'-' -f1)
icon_file=$(find "${DH_ICON_DIR}" -type f -iname "${icon_name// /}.*" | head -n 1)
fi
if [ -z "${icon_file}" ]; then
icon_file="${DH_ICON_DIR}/tux.svg"
fi
DESKTOP_FILE="${DH_CONFIG_DIR}/ready/${VMname}.desktop"
type='Application'
name="${VMname}"
# Try quickget for a more accurate description (old version approach)
comment=$("${SCRIPT_DIR}/qget" --show --plain "${VMname}" 2>$DH_NULL | grep 'Description' | sed 's/^Description:[[:space:]]*//')
[ -z "${comment}" ] && comment=$(get_os_description "${VMname}")
version="${version}"
execmd="quickemu --vm $(desktop_quote_argument "${VMS_DIR}/${vm_conf}")"
icon="${icon_file}"
categories='System;X-Virtualization;'
create_desktop_entry
done
cd "${_old_dir}" || true
find "${DH_CONFIG_DIR}/ready" -type f -name '*.desktop' -exec chmod +x {} + 2>/dev/null || true
echo "[dh] Renew ready complete"
}
function renew_supported_vms() {
echo "[dh] Renew supported..."
local qget_cmd os_info release_edition_options icon_source
# Refresh the user icon cache before rebuilding supported desktop entries.
# New icons added to the repository are otherwise missed until reinstall.
icon_source="${SCRIPT_DIR}/icons"
if [ -d "${icon_source}" ]; then
cp -f "${icon_source}"/* "${DH_ICON_DIR}/" >$DH_NULL 2>$DH_NULL || $root cp -f "${icon_source}"/* "${DH_ICON_DIR}/"
fi
# The repository copy first, then the installed one. The paths are
# absolute so the lookup does not depend on the current directory.
if [ -x "${SCRIPT_DIR}/qget" ]; then
qget_cmd="${SCRIPT_DIR}/qget"
elif [ -x "${PATH_PREFIX}/qget" ]; then
qget_cmd="${PATH_PREFIX}/qget"
else
qget_cmd="qget"
fi
rm -f "${DH_CONFIG_DIR}/supported"/*.desktop >$DH_NULL 2>$DH_NULL
mkdir -p "${DH_CONFIG_DIR}/supported" >$DH_NULL 2>$DH_NULL
"$qget_cmd" --list-os >"${DH_CONFIG_DIR}/supported.md" 2>$DH_NULL
if [ ! -s "${DH_CONFIG_DIR}/supported.md" ]; then
echo "WARNING: qget --list-os produced no entries" >&2
fi
renew_progress "total $(awk 'NF {n++} END {print n+0}' "${DH_CONFIG_DIR}/supported.md")"
# Each worker runs in its own subshell: metadata and desktop fields must
# never leak between distros. Bound network traffic and process count.
local jobs="${DH_RENEW_JOBS:-4}" pid status=0 active=0 completed_dir completed_fd
if [[ ! "$jobs" =~ ^[1-9][0-9]*$ ]]; then
echo "ERROR: DH_RENEW_JOBS must be a positive integer" >&2
return 1
fi
# A completion queue lets ANY finished worker free a slot. Waiting in
# launch order leaves slots idle behind a slow upstream. Use a FIFO so
# this also works on Bash versions without wait -n -p.
completed_dir=$(mktemp -d) || return 1
if ! mkfifo "$completed_dir/done"; then
rmdir "$completed_dir"
return 1
fi
if ! exec {completed_fd}<> "$completed_dir/done"; then
rm -rf "$completed_dir"
return 1
fi
rm -f "$completed_dir/done"
rmdir "$completed_dir"
while IFS= read -r get_name; do
[ -n "$get_name" ] || continue
(
worker_status=0
renew_supported_vm "$get_name" "$qget_cmd" || worker_status=$?
renew_progress "done $get_name"
printf '%s\n' "$BASHPID" >&"$completed_fd"
exit "$worker_status"
) &
active=$((active + 1))
if ((active >= jobs)); then
read -r pid <&"$completed_fd"
wait "$pid" || status=1
active=$((active - 1))
fi
done < "${DH_CONFIG_DIR}/supported.md"
while ((active > 0)); do
read -r pid <&"$completed_fd"
wait "$pid" || status=1
active=$((active - 1))
done
exec {completed_fd}>&-
find "${DH_CONFIG_DIR}/supported" -type f -name '*.desktop' -exec chmod +x {} + 2>/dev/null || true
# Update both monitored views in the same action. Existing VM configs
# may have appeared since the GUI was opened.
renew_progress ready
renew_ready_vms || status=1
echo "[dh] Renew supported complete"
return "$status"
}
# Optional event sink: command-line regeneration works without a progress UI.
function renew_progress() {
if [ -n "${progress_fd:-}" ]; then
printf '%s\n' "$1" 1>&"$progress_fd" 2>/dev/null || true
fi
return 0
}
# One reader serializes completion events from parallel workers. Count actual
# completions (not launch order), reserving one work unit for the ready refresh.
function renew_progress_reader() {
local event total=0 completed=0 percent=0
while IFS= read -r event; do
case "$event" in
'total '*)
total=${event#total }
printf '0\n#Regenerating distros: 0/%s completed\n' "$total"
;;
'done '*)
completed=$((completed + 1))
percent=$((100 * completed / (total + 1)))
printf '%s\n#Regenerating distros: %s/%s completed — %s\n' "$percent" "$completed" "$total" "${event#done }"
;;
ready)
printf '%s\n#Distros: %s/%s completed. Refreshing ready VMs…\n' "$percent" "$completed" "$total"
;;
'finished '*)
if [ "${event#finished }" -eq 0 ]; then
printf '#Regeneration complete: %s/%s distros; ready VMs refreshed.\n100\n' "$completed" "$total"
else
printf '#Regeneration finished with errors: %s/%s distros processed.\n100\n' "$completed" "$total"
fi
;;
esac
done
}
# GUI callbacks run in separate shells. Keep progress and cleanup scoped to
# that action, including failure, interruption and repeated button clicks.
function renew_supported_vms_gui() (
local lock="${DH_CONFIG_DIR}/renew.lock" progress_pid progress_reader_pid progress_fd status=0
if ! mkdir "$lock" 2>/dev/null; then
echo 'Regeneration is already running.' >&2
return 1
fi
trap 'for pid in "${progress_reader_pid:-}" "${progress_pid:-}"; do [ -n "$pid" ] && { kill "$pid" 2>/dev/null || true; wait "$pid" 2>/dev/null || true; }; done; rm -rf "$lock"' EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
# Closing the indicator must not abort an in-flight regeneration.
trap '' PIPE
mkfifo "$lock/progress" "$lock/events" || return 1
# A small, non-modal indicator in the top-right corner stays visible even
# when regeneration was started without a terminal.
yad --progress --auto-close --no-buttons --on-top \
--geometry=300x70-0+0 --title='DistroHopper — regenerating' \
--text='Regenerating supported and ready VMs…' \
--window-icon="${DH_ICON_DIR}/hop.png" < "$lock/progress" &
progress_pid=$!
renew_progress_reader < "$lock/events" > "$lock/progress" 2>/dev/null &
progress_reader_pid=$!
exec {progress_fd}> "$lock/events"
renew_supported_vms || status=$?
renew_progress "finished $status"
exec {progress_fd}>&-
wait "$progress_reader_pid" || true
progress_reader_pid=""
wait "$progress_pid" || true
progress_pid=""
return "$status"
)
# Called only in an isolated worker process.
function renew_supported_vm() {
local get_name="$1" qget_cmd="$2"
VMname=$(echo "${get_name}" | tr ' ' '_')
os_info=$("$qget_cmd" --show --plain "${VMname}" 2>$DH_NULL)
releases=$(printf '%s\n' "${os_info}" | awk -F: '$1 ~ /^[[:space:]]*Releases[[:space:]]*$/ {sub(/^[^:]*:[[:space:]]*/, ""); sub(/[[:space:]]*$/, ""); print; exit}')
editions=$(printf '%s\n' "${os_info}" | awk -F: '$1 ~ /^[[:space:]]*Editions[[:space:]]*$/ {sub(/^[^:]*:[[:space:]]*/, ""); sub(/[[:space:]]*$/, ""); print; exit}')
# The editions one per line. An edition can contain a space (e.g.
# "Brazilian Portuguese"), so the space separated value above cannot
# be split apart again — this list can.
editions_list=$(printf '%s\n' "${os_info}" | sed -n '/^EditionsList:$/,$p' | sed '1d; /^$/d; /^Description:/,$d; /^RSS:/,$d; /^DistroWatch:/,$d')
architectures=$(printf '%s\n' "${os_info}" | awk -F: '$1 ~ /^[[:space:]]*(Archs|Architectures)[[:space:]]*$/ {sub(/^[^:]*:[[:space:]]*/, ""); sub(/[[:space:]]*$/, ""); print; exit}')
# Resolve the icon from the template's ICON field (not the OS name),
# since icon filenames do not always match OS names (e.g. lmde).
template_file="${SCRIPT_DIR}/templates/${VMname}"
if [ ! -f "${template_file}" ]; then
candidate="${VMname}"
while [ -n "${candidate}" ]; do
next="${candidate%-*}"
[ "${next}" = "${candidate}" ] && break
candidate="${next}"
if [ -f "${SCRIPT_DIR}/templates/${candidate}" ]; then
template_file="${SCRIPT_DIR}/templates/${candidate}"
break
fi
done
fi
tmpl_icon=""
if [ -f "${template_file}" ]; then
tmpl_icon=$(OS="${VMname}" bash -c "source '${template_file}' >/dev/null 2>&1; printf '%s' \"\${ICON:-}\"" 2>/dev/null)
fi
if [ -n "${tmpl_icon}" ] && [ -f "${DH_ICON_DIR}/${tmpl_icon}" ]; then
icon_file="${DH_ICON_DIR}/${tmpl_icon}"
elif [ -f "${DH_ICON_DIR}/${VMname}.svg" ]; then
icon_file="${DH_ICON_DIR}/${VMname}.svg"
elif [ -f "${DH_ICON_DIR}/${VMname}.png" ]; then
icon_file="${DH_ICON_DIR}/${VMname}.png"
else
icon_file="${DH_ICON_DIR}/tux.svg"
fi
echo "${VMname}.desktop"
# Check if there are editions
DESKTOP_FILE="${DH_CONFIG_DIR}/supported/${VMname}.desktop"
type="Application"
name="${get_name}"
# Build valid tuples for every architecture and release, not a Cartesian
# product of the default architecture's releases and editions.
local selected_arch selected_release selected_edition arch_info release_info arch_releases
local release_editions_list tuple launcher quoted
release_edition_options=""
for selected_arch in ${architectures:-x86_64}; do
arch_info=$("$qget_cmd" --show --plain --arch "${selected_arch}" "${VMname}" 2>$DH_NULL) || continue
arch_releases=$(printf '%s\n' "${arch_info}" | sed -n 's/^Releases:[[:space:]]*//p')
for selected_release in ${arch_releases}; do
release_info=$("$qget_cmd" --show --plain --arch "${selected_arch}" --release "${selected_release}" "${VMname}" 2>$DH_NULL) || continue
release_editions_list=$(printf '%s\n' "${release_info}" | sed -n '/^EditionsList:$/,$p' | sed '1d; /^$/d; /^Description:/,$d; /^RSS:/,$d; /^DistroWatch:/,$d')
if [ -z "${release_editions_list}" ]; then
printf -v tuple '%s\t%s\t\n' "$selected_arch" "$selected_release"
release_edition_options+="$tuple"
else
while IFS= read -r selected_edition; do
[ -n "$selected_edition" ] || continue
printf -v tuple '%s\t%s\t%s\n' "$selected_arch" "$selected_release" "$selected_edition"
release_edition_options+="$tuple"
done <<< "$release_editions_list"
fi
done
done
[ -n "$release_edition_options" ] || return 1
# Keep the original self-contained inline YAD -> qget launcher. All
# architectures, releases and editions are literal values in Exec.
local arch_items release_items edition_items patterns="" selected_tuple
arch_items=$(printf '%s' "$release_edition_options" | cut -f1 | awk '!seen[$0]++' | paste -sd '!')
release_items=$(printf '%s' "$release_edition_options" | cut -f2 | awk '!seen[$0]++' | paste -sd '!')
edition_items=$(printf '%s' "$release_edition_options" | awk -F '\t' '{v=($3 == "" ? "(none)" : $3); if (!seen[v]++) print v}' | paste -sd '!')
while IFS= read -r selected_tuple; do
[ -n "$selected_tuple" ] || continue
selected_tuple="${selected_tuple//$'\t'/;}"
quoted="'${selected_tuple//\'/\'\\\'\'}'"
patterns+="${patterns:+|}$quoted"
done <<< "$release_edition_options"
# Always confirm before downloading. Fixed values are visible read-only;
# only multiple values get a dropdown. Omit editions entirely if absent.
local variable label items field_type picker="" read_fields=""
launcher=""
for variable in arch release edition; do
case "$variable" in
arch) label=Architecture; items="$arch_items" ;;
release) label=Release; items="$release_items" ;;
edition) label=Edition; items="$edition_items" ;;
esac
if [ "$variable" = edition ] && [ "$items" = '(none)' ]; then
launcher+="edition=''; "
continue
fi
field_type=RO
[[ "$items" != *'!'* ]] || field_type=CB
quoted="'${items//\'/\'\\\'\'}'"
picker+=" --field='$label:$field_type' $quoted"
read_fields+="${read_fields:+ }$variable"
done
launcher+="choice=\$(GDK_BACKEND=x11 yad --form --separator='|' --item-separator='!'$picker --button='Cancel:1' --button='OK:0') || exit 0; "
launcher+="[ -n \"\$choice\" ] || exit 0; IFS='|' read -r $read_fields <<< \"\$choice\"; "
launcher+="[ \"\$edition\" != '(none)' ] || edition=''; "
# Lists contain all choices, but reject mismatched combinations instead
# of silently passing an invalid architecture/release/edition to qget.
launcher+="case \"\$arch;\$release;\$edition\" in $patterns) ;; *) yad --error --text='This combination is not supported.'; exit 1;; esac; "
quoted="'${VMS_DIR//\'/\'\\\'\'}'"
launcher+="mkdir -p $quoted; cd $quoted || exit; "
quoted="'${get_name//\'/\'\\\'\'}'"
launcher+="qget --arch \"\$arch\" $quoted \"\$release\" "
launcher+='${edition:+"$edition"}'
execmd="bash -c $(desktop_quote_argument "$launcher")"
terminal="false"
icon="${icon_file}"
# The initial query already includes the description. Re-querying it in
# template mode repeats potentially expensive upstream release discovery.
comment=$(printf '%s\n' "$os_info" | sed -n 's/^Description:[[:space:]]*//p')
[ -z "${comment}" ] && comment=$(get_os_description "${get_name}")
categories='System;X-Virtualization;'
create_desktop_entry
}
function distrohopper_about() {
echo "[dh] About..."
yad --about --pname=DistroHopper --image="${DH_ICON_DIR}/hop.png" --pversion="${version}" \
--copyright=AGPL3 --comments="random comment" --license=ALGPL3 --authors=zenobit --website=dh.osowoso.org \
--website-label="oSoWoSo"
}
function help_show() {
echo "[dh] Help..."
local help_text
help_text="$(cat <<EOF
DistroHopper v. ${version}
Quick start:
./dh i && dh s g
Arguments:
h help Show this help
d dir Set VMs directory
i install Install DistroHopper
m mode Set mode (tui/gui)
s supported Manage supported VMs
r ready Manage ready-to-run VMs
l language Switch language
Architecture:
The picker shows Architecture, Release and Edition together. Changing
architecture updates releases and editions; changing release updates
editions. Only compatible combinations are offered. The chosen values
are passed to qget when the VM is created.
Metadata source:
Releases and editions come from the generated public/ files, so they
are known without network access. Use 'dh-refresh' to update them, or
switch to the live templates in the Options tab when you need the
current upstream state right away.
Regeneration:
'Renew supported' rebuilds desktop launchers and refreshes ready VMs.
It does not run generate, download ISOs, or upgrade existing VMs.
To discover new releases in public/ mode, run ./dh-refresh (or
./generate --parallel), then click 'Renew supported'. In templates/
mode, releases are queried live. qget downloads an image only after
you select a system and confirm its release/edition.
DH_RENEW_JOBS controls parallel desktop workers (default: 4).
Homepage: dh.osowoso.org
Source: github.com/oSoWoSo/distrohopper
EOF
)"
yad --text-info --title="DistroHopper Help" --window-icon="${DH_ICON_DIR}/hop.png" \
--width=600 --height=500 --center --button="Close":0 \
--fontname="Monospace" --editable=false <<<"$help_text"
}
function set_iso_dir() {
echo "[dh] ISO dir..."
local output status
if [ -n "${ISO_DIR}" ]; then
yad --title="ISO directory" --width=400 \
--text="Shared ISO directory: ${ISO_DIR}" \
--button="Change":0 --button="Disable sharing":1
status=$?
case "${status}" in
0) ;;
1)
ISO_DIR=""
export ISO_DIR
save_config
echo "ISO directory sharing disabled"
return
;;
*) return 1 ;;
esac
fi
output="$(yad --title="ISO directory" --file --directory --width=900 --height=900 \
--text="Choose shared ISO directory" --button="OK":0 --button="Cancel":1 \
--filename="${ISO_DIR:-${VMS_DIR}}")" || return 1
[ -n "${output}" ] || return 1
ISO_DIR="${output}"
export ISO_DIR
save_config
echo "ISO directory set to: ${ISO_DIR}"
}
function set_use_templates() {
echo "[dh] Metadata source..."
local output
output="$(yad --title="Metadata source" --form --separator=$'\t' \
--field="Read releases and editions from templates (live) instead of the generated public/ files":CHK \
"$([ "${USE_TEMPLATES}" == "yes" ] && echo TRUE || echo FALSE)")" || return 1
output="${output//[[:space:]]/}"
case "${output}" in
TRUE) USE_TEMPLATES="yes" ;;
FALSE) USE_TEMPLATES="no" ;;
*) echo "Metadata source: cancelled/unknown (${output})"; return 1 ;;
esac
echo "Metadata source selected: ${output}"
export USE_TEMPLATES
if [ "${USE_TEMPLATES}" == "yes" ]; then
export DH_USE_TEMPLATES="yes"
export DH_USER_TEMPLATES="yes"
else
unset DH_USE_TEMPLATES
unset DH_USER_TEMPLATES
fi
save_config || return 1
echo "Metadata source changed to: ${USE_TEMPLATES}"
echo "Metadata source: $([ "${USE_TEMPLATES}" == "yes" ] && echo templates || echo public)"
yad --title="Metadata source" --width=520 \
--text="$([ "${USE_TEMPLATES}" == "yes" ] && echo "Using templates/: releases and editions are looked up live, which needs network access and is slower." || echo "Using public/: releases and editions come from the generated metadata, which works offline.")"
}
function first_run() {
echo "[dh] Install dh..."
installation_process
echo "Installation done"
echo "Update supported..."
renew_supported_vms
}
function distrohopper_gui() {
export DH_CONFIG_DIR DH_ICON_DIR PATH_PREFIX SCRIPT_DIR TMP_DIR VMS_DIR RAMDISK RAMDISK_DIR ISO_DIR DH_NULL
export progname root version
export -f choose_vms_dir
export -f create_desktop_entry desktop_quote_argument create_dirs dependencies_check_gui desktop_entry_dh
export -f distrohopper_about first_run get_os_description help_show
export -f install_dh install_dependencies install_needed_apt install_needed_dnf install_needed_pacman install_needed_xbps
export -f installation_process renew_ready_vms renew_supported_vms renew_supported_vms_gui renew_supported_vm root_check save_config
export -f renew_progress renew_progress_reader
export -f set_iso_dir set_ramdisk set_vms_directory set_use_templates
# YAD can only monitor directories that already exist when it starts.
mkdir -p "${DH_CONFIG_DIR}/ready" "${DH_CONFIG_DIR}/supported"
renew_ready_vms
local key=$((RANDOM % 9000 + 1000))
yad --plug="${key}" --tabnum=1 --monitor --icons --listen \
--read-dir="${DH_CONFIG_DIR}/ready" --sort-by-name --borders=0 \
--icon-size=46 --item-width=76 --vscroll-policy=always &
yad --plug="${key}" --tabnum=2 --monitor --icons --listen \
--read-dir="${DH_CONFIG_DIR}/supported" --sort-by-name --borders=0 \
--icon-size=46 --item-width=76 --vscroll-policy=always &
yad --plug="${key}" --tabnum=3 --form --cycle-read --use-interp \
--borders=0 --text-align=center --align-buttons \
--field="RAM disk!!Create VM disk in RAM (tmpfs) instead of on disk":FBTN "bash -c 'set_ramdisk'" \
--field="ISO dir!!Set shared ISO directory (or keep in each VM)":FBTN "bash -c 'set_iso_dir'" \
--field="Metadata source!!Use templates (live) or public (offline) for releases and editions":FBTN "bash -c 'set_use_templates'" \
--field="Install dh!!Install DistroHopper":FBTN "bash -c 'first_run'" \
--field="Renew supported!!Rebuild desktop launchers and refresh ready VMs; does not generate metadata or download ISOs":FBTN "bash -c 'renew_supported_vms_gui'" \
--field="Renew ready!!Update ready to run VMs":FBTN "bash -c 'renew_ready_vms'" \
--field="Help!!Show this help":FBTN "bash -c 'help_show'" \
--field="About!!Show info about DistroHopper":FBTN "bash -c 'distrohopper_about'" \
--field="Set VMs directory!!Set default directory where VMs are stored":FBTN "bash -c 'set_vms_directory'" &
yad --notebook --key="${key}" --monitor --listen \
--mouse --selectable-labels --no-buttons \
--window-icon="${DH_ICON_DIR}/hop.png" --width=900 --height=900 \
--title="${progname}" --tab="run VM" --tab="download VM" --tab="Options"
}
run_in_terminal
if [ "${interminal}" = "yes" ]; then
export DH_DEBUG=1
DH_NULL=/dev/stdout
else
DH_NULL=/dev/null
fi
export DH_NULL
wayland_check
root_check
set_variables
# Ensure previously generated desktop entries are executable.
find "${DH_CONFIG_DIR}/ready" "${DH_CONFIG_DIR}/supported" -type f -name '*.desktop' -exec chmod +x {} + 2>/dev/null || true
if [ -f "${DH_CONFIG}" ]; then
echo "Already installed"
else
first_run
echo "Installation finished"
fi
#distrohopper_run_gui
distrohopper_gui