#!/bin/sh

echo "Getting attributes from connect-plug-foo hook"

if ! output=$(snapctl get --slot :foo read); then
    echo "Expected connect-plug-foo to be able to read the value of 'read' attribute of the slot"
    exit 1
fi

PATTERN="read.:\s*.*?/etc"

echo "$output" | grep -Pzq "$PATTERN"

# Read 'newslotattribute' attribute of the slot
if ! output=$(snapctl get --slot :foo newslotattribute); then
    echo "Expected connect-plug-foo be able to read the value of the 'newslotattribute' attribute of the slot"
    exit 1
fi
expected_output="bar"
if [ "$output" != "$expected_output" ]; then
    echo "Expected output to be '$expected_output', but it was '$output'"
    exit 1
fi

# Read 'target' attribute of the slot
if ! output=$(snapctl get --slot :foo target); then
    echo "Expected connect-plug-foo be able to read the value of the 'target' attribute of the slot"
    exit 1
fi
expected_output="slottarget"
if [ "$output" != "$expected_output" ]; then
    echo "Expected output to be '$expected_output', but it was '$output'"
    exit 1
fi

# Read own 'target' attribute
if ! output=$(snapctl get :foo target); then
    echo "Expected connect-plug-foo be able to read the value of own 'target' attribute"
    exit 1
fi
expected_output="plugtarget"
if [ "$output" != "$expected_output" ]; then
    echo "Expected output to be '$expected_output', but it was '$output'"
    exit 1
fi

# Failure on unknown plug
if snapctl get :unknown target; then
    echo "Expected snapctl get to fail on unknown plug"
    exit 1
fi

# Attributes cannot be set in connect- hooks
if snapctl set :foo target=slottarget; then
    echo "Expected snapctl set to fail when run from connect-plug hook"
    exit 1
fi