#!/bin/sh
set -ex

# Flag container environment so cuttlefish host validation skips kvm/group checks in LXC testbed
touch /.dockerenv

echo "=== Verifying /usr/bin/cvd exists and is executable ==="
if [ ! -x /usr/bin/cvd ]; then
    echo "ERROR: /usr/bin/cvd is not executable or does not exist"
    exit 1
fi

echo "=== Testing cvd version ==="
cvd version

echo "=== Testing cvd help ==="
cvd help

echo "=== Verifying cuttlefish-operator system user and service ==="
getent passwd _cutf-operator
if ! service cuttlefish-operator status; then
    service cuttlefish-operator start
fi
service cuttlefish-operator status

for cert_file in \
    /etc/cuttlefish-common/operator/cert/cert.pem \
    /etc/cuttlefish-common/operator/cert/key.pem; do
    if [ ! -s "$cert_file" ]; then
        echo "ERROR: expected generated TLS file $cert_file"
        exit 1
    fi
done

echo "=== Probing live cuttlefish-operator HTTP/HTTPS endpoints ==="
curl -fsS http://127.0.0.1:1080/infra_config | grep -q 'ice_servers'
curl -fsSk https://127.0.0.1:1443/ | grep -q '<app-root>'

echo "=== autopkgtest for cvd and cuttlefish-operator passed successfully! ==="
