#!/bin/sh

set -ex

# required for the debian adt host
mkdir -p /etc/systemd/system/snapd.service.d/
if [ "${http_proxy:-}" != "" ]; then
    cat <<EOF | tee /etc/systemd/system/snapd.service.d/proxy.conf
[Service]
Environment=http_proxy=$http_proxy
Environment=https_proxy=$http_proxy
EOF

    # ensure environment is updated
    echo "http_proxy=$http_proxy" >> /etc/environment
    echo "https_proxy=$http_proxy" >> /etc/environment
fi
systemctl daemon-reload

# ensure we are not get killed too easily
printf '%s\n' "-950" > /proc/$$/oom_score_adj

# see what mem we have (for debugging)
cat /proc/meminfo

# ensure we can do a connect to localhost
echo ubuntu:ubuntu|chpasswd
sed -i 's/\(PermitRootLogin\|PasswordAuthentication\)\>.*/\1 yes/' /etc/ssh/sshd_config
systemctl reload sshd.service

# Map snapd deb package pockets to core snap channels. This is intended to cope
# with the autopkgtest execution when testing packages from the different pockets
if apt -qq list snapd | grep -q -- -proposed; then
    export SPREAD_CORE_CHANNEL=candidate
elif apt -qq list snapd | grep -q -- -updates; then
    export SPREAD_CORE_CHANNEL=stable
fi
# ensure we always run from the deb that is currently tested
export SNAP_REEXEC=0
mkdir -p /etc/systemd/system/snapd.service.d
cat <<EOF > /etc/systemd/system/snapd.service.d/no-reexec.conf
[Service]
Environment=SNAP_REEXEC=$SNAP_REEXEC
EOF
systemctl daemon-reload
systemctl restart snapd

# Spread will only buid with recent go
snap install --classic go

# and now run spread against localhost
export GOPATH=/tmp/go
/snap/bin/go get -u github.com/snapcore/spread/cmd/spread

# the tests need this:
groupadd --gid 12345 test
adduser --uid 12345 --gid 12345 --disabled-password --gecos '' test

# we build our own minimal spread.yaml
cat > spread.yaml <<'EOF'
project: snapd
path: /home/gopath/src/github.com/snapcore/snapd
environment:
    PROJECT_PATH: /home/gopath/src/github.com/snapcore/snapd
    TESTSLIB: $PROJECT_PATH/tests/lib
    SNAPPY_TESTING: 1
    PATH: $PATH:$PROJECT_PATH/tests/lib/bin
backends:
    autopkgtest:
        type: adhoc
        allocate: ADDRESS localhost:22
        systems:
        - adt-local:
            username: ubuntu
            password: ubuntu
suites:
        tests/smoke/:
            summary: Essenial system level tests for snapd
EOF
/tmp/go/bin/spread -v autopkgtest:adt-local:tests/smoke/

# store journal info for inspectsion
journalctl --sync
journalctl -ab > "$ADT_ARTIFACTS"/journal.txt
