#!/bin/bash
# Signal Triple-C to perform host-side AWS SSO login, then sync the result.
CACHE_DIR="$HOME/.aws/sso/cache"
HOST_CACHE="/tmp/.host-aws/sso/cache"
MARKER="/tmp/.sso-refresh-marker"

touch "$MARKER"

# Emit marker for Triple-C app to detect in terminal output
echo "###TRIPLE_C_SSO_REFRESH###"
echo "Waiting for SSO login to complete on host..."

TIMEOUT=120
ELAPSED=0
while [ $ELAPSED -lt $TIMEOUT ]; do
    if [ -d "$HOST_CACHE" ]; then
        NEW=$(find "$HOST_CACHE" -name "*.json" -newer "$MARKER" 2>/dev/null | head -1)
        if [ -n "$NEW" ]; then
            mkdir -p "$CACHE_DIR"
            cp -f "$HOST_CACHE"/*.json "$CACHE_DIR/" 2>/dev/null
            chown -R "$(whoami)" "$CACHE_DIR"
            echo "AWS SSO credentials refreshed successfully."
            rm -f "$MARKER"
            exit 0
        fi
    fi
    sleep 2
    ELAPSED=$((ELAPSED + 2))
done

echo "SSO refresh timed out (${TIMEOUT}s). Please try again."
rm -f "$MARKER"
exit 1
