#!/bin/bash
set -e

GREEN='\033[0;32m'; BLUE='\033[0;34m'; RED='\033[0;31m'; NC='\033[0m'
TOKEN=$1

if [ -z "$TOKEN" ]; then
    echo -e "${BLUE}Usage: sudo bash enterprise-install.sh <enrollment_token>${NC}"
    exit 1
fi

echo -e "${BLUE}ð Authenticating with SAILLENT Authority...${NC}"
ENROLL_RESP=$(curl -s -X POST https://license.saillent.com/v1/enroll -H "Content-Type: application/json" -d "{\"token\":\"$TOKEN\"}")

INSTALL_ID=$(echo "$ENROLL_RESP" | python3 -c 'import sys,json;print(json.load(sys.stdin)["license"]["installation_id"])' 2>/dev/null)
ORG_NAME=$(echo "$ENROLL_RESP" | python3 -c 'import sys,json;print(json.load(sys.stdin)["license"]["organization"])' 2>/dev/null)

if [ -z "$INSTALL_ID" ]; then
    echo -e "â ${RED}Enrollment failed. Token is invalid, used, or expired.${NC}"
    echo -e "Response: $ENROLL_RESP"
    exit 1
fi

echo -e "${GREEN}â Authenticated for: $ORG_NAME${NC}"
echo -e "${BLUE}ð¥ Downloading SAILLENT Agent...${NC}"
sudo mkdir -p /opt/saillent
sudo curl -s -o /opt/saillent/saillent-agent https://license.saillent.com/v1/download
sudo chmod +x /opt/saillent/saillent-agent

echo -e "${BLUE}âï¸ Writing Node Configuration...${NC}"
cat << 'CONFIG' | sudo tee /opt/saillent/config.yaml > /dev/null
server:
  listen_addr: "0.0.0.0"
  port: 3000
  upstream_url: "http://127.0.0.1:4000"
  admin_api_key: "local-node-secret"
gitops:
  repo_url: "https://github.com/AlBochi/selligent-policies.git"
  branch: "main"
  poll_interval_secs: 60
  local_clone_path: "/opt/saillent/policies"
database:
  path: "/opt/saillent/saillent.db"
CONFIG


echo -e "${BLUE}âï¸ Configuring Zero-Trust Daemon...${NC}"
cat << WRAPPER | sudo tee /opt/saillent/run.sh > /dev/null
#!/bin/bash
INSTALL_ID="$INSTALL_ID"
/opt/saillent/saillent-agent &
AGENT_PID=\$!
while kill -0 \$AGENT_PID 2>/dev/null; do
    sleep 10
    STATUS=\$(curl -s -X POST https://license.saillent.com/v1/heartbeat -H "Content-Type: application/json" -d "{\"installation_id\":\"\$INSTALL_ID\"}" | python3 -c 'import sys,json;print(json.load(sys.stdin)["status"])' 2>/dev/null)
    if [ "\$STATUS" = "revoked" ]; then
        echo "ð License Revoked. Shutting down."
        kill \$AGENT_PID
        exit 0
    fi
done
WRAPPER
sudo chmod +x /opt/saillent/run.sh

cat << 'SERVICE' | sudo tee /etc/systemd/system/saillent.service > /dev/null
[Unit]
Description=SAILLENT Zero-Trust AI Firewall
[Service]
ExecStart=/opt/saillent/run.sh
Restart=always
[Install]
WantedBy=multi-user.target
SERVICE

sudo systemctl daemon-reload
sudo systemctl enable saillent > /dev/null 2>&1
sudo systemctl restart saillent

echo -e "${GREEN}======================================================${NC}"
echo -e "${GREEN}  ð¡ï¸  SAILLENT ENTERPRISE NODE ACTIVE ð¡ï¸  ${NC}"
echo -e "${GREEN}======================================================${NC}"
echo -e "Installation ID: $INSTALL_ID"
echo -e "Status: ${GREEN}Enforcing Zero-Trust${NC}"
