#!/bin/sh
#
# The Qubes OS Project, http://www.qubes-os.org
#
# Copyright (C) 2018 max <3752128+maximilize@users.noreply.github.com>
# Copyright (C) 2018 Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#

cd /var/lib/snapd/snaps/ || exit 1

if [ -d /snap ]; then
    target_dir=/snap
elif [ -d /var/lib/snapd/snap ]; then
    target_dir=/var/lib/snapd/snap
else
    echo "Can't find snap target mount dir" >&2
    exit 1
fi

ls *.snap | cut -d'.' -f1 | sed 's/_/ /' | \
while read app revision; do
    unit_name=$(systemd-escape -p "${target_dir}/${app}/${revision}")
    if [ ! -e /etc/systemd/system/$unit_name.mount ]; then
        cat >/etc/systemd/system/$unit_name.mount <<EOF
[Unit]
Description=Mount unit for ${app}, revision ${revision}
Before=snapd.service

[Mount]
What=/var/lib/snapd/snaps/${app}_${revision}.snap
Where=${target_dir}/${app}/${revision}
Type=squashfs
Options=nodev,ro,x-gdu.hide

[Install]
WantedBy=multi-user.target
EOF
        systemctl -q enable $unit_name.mount
        systemctl -q start $unit_name.mount
    fi
done
