summary: Ensure remove-user functionality

details: |
    Check the command `snap remove-user` works properly. Verify that
    it fails when run as non-root user without sudo and works when run
    as non-root user with sudo. Also Verify the root user cannot be
    removed.

systems: [ubuntu-core-*]

environment:
    # Note that any valid sso account will work for this test
    USER_EMAIL: mvo@ubuntu.com
    USER_NAME: mvo

prepare: |
    # Note: make this test work with the user already created in the device
    if [ "$(snap managed)" = "true" ]; then
        # Leave a file indicating the device was initially managed
        touch managed.device

        exit 0
    fi
    snap create-user --sudoer "$USER_EMAIL"

restore: |
    if [ -e managed.device ]; then
        exit 0
    fi
    userdel --extrausers -r "$USER_NAME" || true
    rm -rf "/etc/sudoers.d/create-user-$USER_NAME"

execute: |
    if [ -e managed.device ]; then
        exit 0
    fi

    echo "precondition check: user in passwd"
    id "$USER_NAME"
    echo "precondition check: has sudoer file"
    test -f "/etc/sudoers.d/create-user-$USER_NAME"
    echo "precondition check: user has a home" 
    test -d "/home/$USER_NAME"

    echo "snap remove-user fails when run as non-root user without sudo"
    expected="error: access denied (try with sudo)"
    if obtained=$(su - test /bin/sh -c "snap remove-user $USER_NAME 2>&1"); then
        echo "remove-user command should have failed"
    fi
    [ "$obtained" = "$expected" ]

    echo "snap remove-user needs root and snap login is not enough"
    if [ -n "$SPREAD_STORE_USER" ] && [ -n "$SPREAD_STORE_PASSWORD" ]; then
        echo "Checking successful login"
        expect -d -f "$TESTSLIB"/successful_login.exp

        expected="error: access denied (try with sudo)"
        if obtained=$(su - test /bin/sh -c "snap remove-user $USER_NAME 2>&1"); then
            echo "remove-user command should have failed"
        fi
        [ "$obtained" = "$expected" ]
    fi

    echo "snap remove-user succeeds when run as non-root user with sudo"
    expected="removed user \"$USER_NAME\""
    obtained=$(su - test /bin/sh -c "sudo snap remove-user $USER_NAME 2>&1")
    [ "$obtained" = "$expected" ]

    echo "user no longer in passwd"
    not id "$USER_NAME"
    echo "user no longer has sudoer file"
    test ! -f "/etc/sudoers.d/create-user-$USER_NAME"
    echo "user no longer has a home"
    test ! -d "/home/$USER_NAME"

    echo "user is no longer managed by snapd"
    [ "$(snap managed)" = "false" ]

    echo "snap remove-user cannot remove arbitrary users"
    expected="error: user \"root\" is not known"
    if obtained=$(su - test /bin/sh -c "sudo snap remove-user root 2>&1"); then
        echo "remove-user command should have failed"
    fi
    [ "$obtained" = "$expected" ]
