#!/bin/sh

set -e

rm -f /tmp/local_127.0.0.1.cfg

cleanup() {
    if [ -n "$SERVER_PID" ]; then
        kill -9 "$SERVER_PID" 2>/dev/null || true
        wait "$SERVER_PID" 2>/dev/null || true
    fi
}

trap cleanup EXIT

echo "[*] Generate config"
sliver-server operator --name local --lhost 127.0.0.1 --save /tmp/local_127.0.0.1.cfg --permissions all

echo "[*] Start sliver-server"
sliver-server daemon &
SERVER_PID=$!

sleep 10

echo "[*] Import config into sliver-client"
sliver-client import /tmp/local_127.0.0.1.cfg 2>/dev/null

echo "[*] Run sliver-client and connect to sliver-server"
timeout 10 sliver-client >/tmp/output.txt || true

grep 'Welcome to the sliver shell' /tmp/output.txt || {
    cat /tmp/output.txt
    exit 1
}
