#!/bin/sh
# snapcraft reset script
# distributed under LGPL v2

if [ ! -e /var/lib/dpkg/status ]; then
    echo "This script only works on Ubuntu Classic"
    exit 1
fi

if [ "$(id -u)" != 0 ]; then
    echo "This script needs to be run as root"
    exit 1
fi

echo "This script will permanently destroy and reset all state in snapd"
echo "You will lose all of your installed snaps"
echo
echo "Type: DESTROY to remove all of your snap state"
echo
read consent

if [ "$consent" != "DESTROY" ]; then
    echo "No consent, aborting"
    exit 0
fi
echo
echo "ABOUT TO DESTROY ALL OF STATE OF SNAPD"
echo
echo "Interrupt the script in 10 seconds to abort"
sleep 10 || exit
echo
echo "DESTROYING ALL STATE OF SNAPD"

if systemctl is-active --quiet snapd.service snapd.socket; then
    snapd_was_active=yes
    echo
    echo "Stopping snapd..."
    echo
    (
        set -x
        systemctl stop snapd.socket snapd.service
    )
else
    echo "Skipping stopping snapd as systemctl reports it's inactive."
fi

echo
echo "Unmounting all snaps..."
echo
(
    set -x
    umount /var/lib/snapd/snaps/*.snap
)

echo
echo "Removing all support files and state..."
echo
(
    set -x
    rm -rvf /var/lib/snapd/*
)

echo
echo "Removing generated systemd units..."
echo
(
    set -x
    rm -vf /etc/systemd/system/snap-*.mount
    rm -vf /etc/systemd/system/snap-*.service
    rm -vf /etc/systemd/system/multi-user.target.wants/snap-*.mount
)

echo
echo "Removing generated executable wrappers..."
echo
(
    set -x
    rm -vrf /snap/*
)

if [ "$snapd_was_active" = "yes" ]; then
    echo
    echo "Starting snapd"
    (
        set -x
        systemctl start snapd.socket
    )
fi
