summary: Run test to ensure snaps can store data on ubuntu-save partition

details: |
    This test verifies that a folder is created for newly installed snaps on the
    ubuntu-save partition. It then verifies that we can write data to that folder
    and that the folder is removed again once the snap is removed.

systems: [ubuntu-2*]

debug: |
    remote.exec "lsblk" || true

execute: |
    echo "Wait for the system to be seeded first"
    remote.exec "sudo snap wait system seed.loaded"

    echo "Ensuring the presence of ubuntu-save"
    remote.exec "blkid -L ubuntu-save"

    echo "Ensuring the path /var/lib/snapd/save exists"
    remote.exec "ls -l /var/lib/snapd/save"

    # next up is to install a snap and verify the creation of a snap save folder
    # for that snap on the ubuntu-save partition
    remote.exec "sudo snap install test-snapd-sh"

    echo "Ensuring the path /var/lib/snapd/save/snap now exists"
    remote.exec "ls -l /var/lib/snapd/save/snap"

    echo "Ensuring the path /var/lib/snapd/save/snap/test-snapd-sh now exists"
    remote.exec "ls -l /var/lib/snapd/save/snap/test-snapd-sh"

    # instance environment variables are correctly set up
    remote.exec "snap run test-snapd-sh.sh -c 'env' test" | MATCH 'SNAP_SAVE_DATA=/var/lib/snapd/save/snap/test-snapd-sh'

    echo "Ensuring we can write a file to /var/lib/snapd/save/snap/test-snapd-sh"
    remote.exec "sudo snap run test-snapd-sh.sh -c \"echo 'hello world' > /var/lib/snapd/save/snap/test-snapd-sh/hello.txt\""

    echo "Verify contents of the file directly to make sure file was written"
    remote.exec "grep -q 'hello world' '/run/mnt/ubuntu-save/snap/test-snapd-sh/hello.txt'"

    echo "Ensuring we cannot write a file to /var/lib/snapd/save/snap"
    if remote.exec "sudo snap run test-snapd-sh.sh -c \"echo 'hello world' > /var/lib/snapd/save/snap/hello.txt\""; then
        tests.nested fail "Writing to /var/lib/snapd/save/snap/hello.txt should have failed"
    fi

    echo "Removing the snap again and making sure that the save folder is removed"
    remote.exec "sudo snap remove test-snapd-sh"

    echo "Ensuring the path /var/lib/snapd/save/snap/test-snapd-sh no longer exists"
    remote.exec "\[ ! -d \"/var/lib/snapd/save/snap/test-snapd-sh\" \]"
