#!/bin/bash

if [ "${EUID}" -ne 0 ]; then
    echo "Please run this script as superuser!"
    exit 1
fi

show_help() {
    SRIPT_NAME="$(basename ${0})"
    echo "${SRIPT_NAME} -- reset all waydroid files to initial state

This is a simple script for cleaning all waydroid artifacts from users directories. It allows to bring waydroid to the same state as it was just after installation in the first time.

Usage:
${SRIPT_NAME}
${SRIPT_NAME} <option>

If <option> is not set then script creates temporary systemd service which will be called one time after system reboot and then removed just after execution.

Options:
    -h, --help      Show this help and exit
    -r, --reset     Reset all waydroid files to initial state immediately
"
}

SERVICE_FILE="/etc/systemd/system/waydroid-cleaning.service"

reset_waydroid() {
    # Remove data from home directory
    rm -rf /home/*/.local/share/applications/*waydroid*
    rm -rf /home/*/.local/share/waydroid

    # Reset common settings set by waydroid kcm
    systemctl enable waydroid-container.service 2> /dev/null || true
    rm -f /etc/astra-mobile/astra-mobile-waydroid.ini

    systemctl disable waydroid-cleaning
    rm ${SERVICE_FILE}
}

if [ "${1}" = "-h" ] || [ "${1}" = "--help" ] ; then
    show_help
    exit 0
elif [ "${1}" = "-r" ] || [ "${1}" = "--reset" ] ; then
    reset_waydroid
    exit 0
elif [ ! -z "${1}" ] ; then
    echo "Error: unsupported option!"
    echo
    show_help
    exit 1
fi

SCRIPT_FILE="$(realpath ${0})"

cat > ${SERVICE_FILE} <<EOF
[Unit]
Description=Reset all waydroid files to initial state
RequiresMountsFor=/home

[Install]
WantedBy=multi-user.target

[Service]
Type=simple
ExecStart=${SCRIPT_FILE} -r
EOF
systemctl enable waydroid-cleaning || exit 2

echo
echo "All changes will be applied after the next reboot!"
