#!/usr/bin/env bash

set -euo pipefail

# Configurazione (override con variabili d'ambiente prima di eseguire lo script)
KUBEEDGE_VERSION="${KUBEEDGE_VERSION:-v1.22.0}"
CLOUD_MASTER_IP="${CLOUD_MASTER_IP:-89.105.78.161}"
EDGE_NODE_NAME="${EDGE_NODE_NAME:-edge-node-02}"
KUBEEDGE_TOKEN="${KUBEEDGE_TOKEN:-26477f03e3d0209870acdf724478f1d875e1328f8ea3408d74f3d7d109ad02be.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NzQ5OTI1NzB9.YxfikSixBrX7bvQxgxXYpbwLJHg0SAQ9mQ7kblBWQrk}"

CONTAINERD_VERSION="1.6.14"
RUNC_VERSION="1.1.3"
CNI_VERSION="1.1.1"

echo "==== EDGE NODE INSTALL START ===="
echo "KUBEEDGE_VERSION=${KUBEEDGE_VERSION}"
echo "CLOUD_MASTER_IP=${CLOUD_MASTER_IP}"
echo "EDGE_NODE_NAME=${EDGE_NODE_NAME}"
echo "KUBEEDGE_TOKEN=${KUBEEDGE_TOKEN}"
if ! command -v sudo >/dev/null 2>&1; then
  echo "Errore: sudo non trovato"
  exit 1
fi

TMP_DIR="$(mktemp -d)"
trap 'rm -rf "${TMP_DIR}"' EXIT

echo "[1/8] Download e installazione containerd ${CONTAINERD_VERSION}"
cd "${TMP_DIR}"
wget -q "https://github.com/containerd/containerd/releases/download/v${CONTAINERD_VERSION}/containerd-${CONTAINERD_VERSION}-linux-amd64.tar.gz"
sudo tar Cxzvf /usr/local "containerd-${CONTAINERD_VERSION}-linux-amd64.tar.gz"

echo "[2/8] Download e installazione runc ${RUNC_VERSION}"
wget -q "https://github.com/opencontainers/runc/releases/download/v${RUNC_VERSION}/runc.amd64"
sudo install -m 755 runc.amd64 /usr/local/sbin/runc

echo "[3/8] Download e installazione CNI plugins ${CNI_VERSION}"
wget -q "https://github.com/containernetworking/plugins/releases/download/v${CNI_VERSION}/cni-plugins-linux-amd64-v${CNI_VERSION}.tgz"
sudo mkdir -p /opt/cni/bin
sudo tar Cxzvf /opt/cni/bin "cni-plugins-linux-amd64-v${CNI_VERSION}.tgz"

echo "[4/8] Configurazione containerd"
sudo mkdir -p /etc/containerd
containerd config default | sudo tee /etc/containerd/config.toml >/dev/null
sudo sed -i '/SystemdCgroup = true/d' /etc/containerd/config.toml
sudo curl -fsSL https://raw.githubusercontent.com/containerd/containerd/main/containerd.service -o /etc/systemd/system/containerd.service

echo "[5/8] Configurazione rete CNI"
sudo mkdir -p /etc/cni/net.d
cat <<'EOF' | sudo tee /etc/cni/net.d/10-containerd-net.conflist >/dev/null
{
  "cniVersion": "1.0.0",
  "name": "containerd-net",
  "plugins": [
    {
      "type": "bridge",
      "bridge": "cni0",
      "isGateway": true,
      "ipMasq": true,
      "promiscMode": true,
      "ipam": {
        "type": "host-local",
        "ranges": [
          [{
            "subnet": "10.88.0.0/16"
          }],
          [{
            "subnet": "2001:db8:4860::/64"
          }]
        ],
        "routes": [
          { "dst": "0.0.0.0/0" },
          { "dst": "::/0" }
        ]
      }
    },
    {
      "type": "portmap",
      "capabilities": {"portMappings": true}
    }
  ]
}
EOF

echo "[6/8] Avvio e abilitazione containerd"
sudo systemctl daemon-reload
sudo systemctl enable --now containerd

echo "[7/8] Installazione keadm ${KUBEEDGE_VERSION}"
cd "${TMP_DIR}"
curl -fsSL "https://github.com/kubeedge/kubeedge/releases/download/${KUBEEDGE_VERSION}/keadm-${KUBEEDGE_VERSION}-linux-amd64.tar.gz" | tar -xz
sudo mv "keadm-${KUBEEDGE_VERSION}-linux-amd64/keadm/keadm" /usr/local/bin/

echo "[8/8] Join edge node al cloud master"
sudo keadm join \
  --cloudcore-ipport="${CLOUD_MASTER_IP}:10000" \
  --edgenode-name="${EDGE_NODE_NAME}" \
  --token="${KUBEEDGE_TOKEN}" \
  --kubeedge-version="${KUBEEDGE_VERSION}"

echo "Creazione script di cleanup edge"
cat <<'EOF' | sudo tee /usr/local/bin/edge-cleanup.sh >/dev/null
#!/usr/bin/env bash

set -euo pipefail

echo "==== EDGE NODE CLEANUP START ===="
echo "Timestamp: $(date)"

echo "[1] Checking orphan processes..."
ORPHANS=$(ps -eo pid,ppid,cmd | awk '$2 == 1 {print $1}')
for PID in ${ORPHANS}; do
  if [ "${PID}" != "1" ]; then
    echo "Killing orphan PID: ${PID}"
    kill -9 "${PID}" 2>/dev/null || true
  fi
done

echo "[2] Cleaning containerd..."
if command -v crictl >/dev/null 2>&1; then
  crictl ps -a --state Exited -q | xargs -r crictl rm || true
  crictl pods --state NotReady -q | xargs -r crictl rmp || true
  crictl rmi --prune || true
else
  echo "crictl not found, skipping..."
fi

echo "[3] Restarting containerd..."
systemctl restart containerd || true

echo "[4] Cleaning kubelet state (soft)..."
find /var/lib/kubelet/pods -mindepth 1 -maxdepth 1 -type d -mtime +1 -exec rm -rf {} + || true

echo "[5] Restarting kubelet + edgecore..."
systemctl restart kubelet || true
systemctl restart edgecore || true

echo "[6] Checking MQTT port..."
ss -tulnp | grep 1883 || echo "WARNING: Mosquitto not listening"

echo "==== EDGE NODE CLEANUP DONE ===="
EOF

sudo chmod +x /usr/local/bin/edge-cleanup.sh

echo "Creazione service systemd edge-cleanup"
cat <<'EOF' | sudo tee /etc/systemd/system/edge-cleanup.service >/dev/null
[Unit]
Description=Edge Node Cleanup
After=network.target

[Service]
Type=oneshot
ExecStart=/usr/local/bin/edge-cleanup.sh
RemainAfterExit=true

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable edge-cleanup

echo "==== EDGE NODE INSTALL DONE ===="
