#!/bin/bash
# Info: Script to install/create/delete/update cilium from file settings 
# Author: JesusPerezLorenzo  
# Release: 1.0 
# Date: 12-11-2024

USAGE="install.sh install | update | remvoe"
[ "$1" == "-h"  ] && echo "$USAGE"  && exit 1

OS=$(uname | tr '[:upper:]' '[:lower:]')
ARCH="$(uname -m | sed -e 's/x86_64/amd64/' -e 's/\(arm\)\(64\)\?.*/\1\2/' -e 's/aarch64$/arm64/')"

CILIUM_CLI_VERSION=${CILIUM_CLI_VERSION:-$(curl -s https://raw.githubusercontent.com/cilium/cilium-cli/master/stable.txt)}
CILIUM_URL="https://github.com/cilium/cilium-cli/releases/download"

_cilium_init() {
  local curr_version
  curr_version=$(cilium version 2>/dev/null | grep cli | awk '{ print $2 }')
  if [ "$curr_version" !=  "${CILIUM_CLI_VERSION}" ]  ; then 
    curl -sL --remote-name-all "$CILIUM_URL/${CILIUM_CLI_VERSION}/cilium-${OS}-${ARCH}.tar.gz"{,.sha256sum} 
    # sha256sum --check cilium-${OS}-${ARCH}.tar.gz.sha256sum
    sudo tar xzfC "cilium-${OS}-${ARCH}.tar.gz" /usr/local/bin
    rm cilium-"${OS}"-"${ARCH}".tar.gz{,.sha256sum}
  fi
}
_cilium_delete() {
  sudo cilium uninstall
}
_cilium_install() {
  [ "$K8S_MODE" == "image" ] && return 0
  local status
  status=$(cilium  status 2>/dev/null | grep Operator | awk '{print $4}')
  [[ "$status" == *OK* ]] && return 0
  #if ! sudo /usr/local/bin/cilium install --cluster-name $CLUSTER_NAME ; then 
  if ! /usr/local/bin/cilium install &>/dev/null; then 
    echo "Error installing cilium $?"
    exit 1
  fi
}
_cilium_update() {
  sudo cilium update  
}

if [ "$TSKSRVC" == "remove" ] ; then
  _cilium_delete
  exit
fi
[ "$TSKSRVC"  == "update" ] &&  _cilium_update && exit 0
if ! _cilium_init ; then
  echo "error cilium init"
  exit 1
fi
if ! _cilium_install ; then
  echo "error cilium install"
  exit 1
fi
