#!/bin/bash

## Copyright (C) 2019 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

## Similar to live-mode-to-read-only.

## Keep the command trace: it is this script's diagnostic output.
set -x
set -o errexit
set -o nounset
set -o pipefail
set -o errtrace
shopt -s inherit_errexit
shopt -s shift_verbose
export LC_ALL=C

## No ERR trap by design. errexit cannot be prevented from exiting the script
## by a trap, the script would exit immediately after the handler finishes
## execution.

exit_code="0"

# shellcheck source=../../../../helper-scripts/usr/libexec/helper-scripts/live-mode.sh
source "${HELPER_SCRIPTS_PATH:-}"/usr/libexec/helper-scripts/live-mode.sh

## Assigned by the sourced live-mode.sh above.
# shellcheck disable=SC2154
if [ "${live_status_detected}" = "true" ]; then
   ## Live mode.
   true "${0}: INFO: Live mode detected. Doing nothing. Exiting."
   exit 0
fi
## Persistent mode.

## VM names are provided in the second column of the table virsh outputs. The
## table has two header lines we must skip.
vm_names_list="$(virsh list --all | awk 'NR>2 {print $2}')" || exit_code="1"

## Deliberate word splitting: vm_names_list is a newline-separated list.
# shellcheck disable=SC2086
for vm_name_item in ${vm_names_list} ; do
   virt-xml "${vm_name_item}" --edit --disk readonly=off || exit_code="1"
done

## Guarded by 'test -f' to match live-mode-to-read-only: a not-installed VM
## image is skipped rather than counted as a chmod failure.
if test -f "/var/lib/libvirt/images/Whonix-Gateway.qcow2" ; then
   chmod --verbose --recursive ug+w "/var/lib/libvirt/images/Whonix-Gateway.qcow2" || exit_code="1"
fi
if test -f "/var/lib/libvirt/images/Whonix-Workstation.qcow2" ; then
   chmod --verbose --recursive ug+w "/var/lib/libvirt/images/Whonix-Workstation.qcow2" || exit_code="1"
fi

exit "${exit_code}"
