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-20.04-64, ubuntu-22.04-64]

debug: |
    tests.nested exec "lsblk"

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

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

    echo "Ensuring the path /var/lib/snapd/save exists"
    tests.nested 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
    tests.nested exec "sudo snap install test-snapd-sh"

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

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

    # instance environment variables are correctly set up
    tests.nested 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"
    tests.nested 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"
    tests.nested 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 tests.nested 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"
    tests.nested exec "sudo snap remove test-snapd-sh"

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