summary: Ensure that snap create-user works in ubuntu-core
# FIXME: combine this test with tests/core/create-user-2?

details: |
    Check that the command `snap create-user` works in ubuntu core.
    Ensure that the keys are imported for the user and it can be created as a sudoer.

environment:
    USER_EMAIL: mvo@ubuntu.com
    USER_NAME: mvo

restore: |
    if [ -e managed.device ]; then
        exit 0
    fi
    # Check if the user exists before remove it
    if id "$USER_NAME" >/dev/null 2>&1; then
        snap remove-user "$USER_NAME"
    fi

debug: |
    if [ -e managed.device ]; then
        ls -al /home/"$USER_NAME" || true
        cat /var/lib/extrausers/passwd || true
    fi

execute: |
    if [ "$(snap managed)" = "true" ]; then
        # Leave a file indicating the device was initially managed
        touch managed.device

        if snap create-user --sudoer "$USER_EMAIL" 2>create.error; then
            echo "Did not get expected error creating user in managed device"
            exit 1
        fi
        MATCH "cannot create user: device already managed" < create.error

        exit 0
    fi

    echo "Adding invalid user"
    expected='error: while creating user: cannot create user "nosuchuser@example.com"'
    if output=$(snap create-user nosuchuser@example.com 2>&1); then
        echo "snap create-user should fail for unknown users but it did not"
        exit 1
    fi
    MATCH "$expected" <<<"$output"

    echo "Adding valid user"
    expected="created user \"$USER_NAME\""
    output=$(snap create-user --sudoer "$USER_EMAIL")
    if [ "$output" != "$expected" ]; then
        echo "Unexpected output $output"
        exit 1
    fi
    echo "Ensure there are ssh keys imported"
    MATCH ssh-rsa < /home/"$USER_NAME"/.ssh/authorized_keys

    echo "Ensure the user is a sudo user"
    sudo -u "$USER_NAME" sudo true

    echo "ensure the user's home directory exists"
    test -d /home/"$USER_NAME"

    echo "ensure ~/.snap/auth.json was created"
    test -f /home/"$USER_NAME"/.snap/auth.json

    echo "ensure user's email was stored in ~/.snap/auth.json"
    MATCH "\"email\":\"$USER_EMAIL\"" < /home/"$USER_NAME"/.snap/auth.json
