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

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

[ -r "env-kubectl" ] && . env-kubectl

[ -z "$VERSION" ] && echo "No VERSION value " && exit 1

export LC_CTYPE=C.UTF-8 
export LANG=C.UTF-8
cmd_out=/dev/null

[ -n "$1" ] && CMD_TSK=$1 && shift

_install_kubectl() {
  [ -z "$VERSION" ] || [ -z "$ARCH" ] || [ -z "$URL" ] || [ -z "$FILE" ] && exit 1
  _check_resolution
  curr_vers=$(kubectl version 2>/dev/null | grep Client | awk '{print $3}' | sed 's/^v//g' 2>/dev/null)
  #sudo chmod 1777 /tmp 
  if [ "v$curr_vers" != "$K8S_VERSION" ]; then
    echo "Install packages"
    if [ "$CMD_TSK" != "update" ] && [ ! -r "/etc/apt/keyrings/kubernetes-apt-keyring.gpg" ]; then
      sudo apt-get update && sudo apt-get install -y apt-transport-https gnupg2 curl
      curl -fsSL https://pkgs.k8s.io/core:/stable:/v$MAJOR_VERSION/deb/Release.key | sudo gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg
      echo "deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://pkgs.k8s.io/core:/stable:/v$MAJOR_VERSION/deb/ /" | sudo tee /etc/apt/sources.list.d/kubernetes.list
    fi
    _off_swap
    sudo apt-get update -q 
    sudo apt-mark unhold kubectl 
    if ! sudo apt-get install -y kubectl ; then
      echo "error installing kubernetes"
      return 1
    fi
    # Hold your horse !
    sudo apt-mark hold kubectl 
    echo "init done"
  fi
}
case "$CMD_TSK" in 
  remove)
    suto apt-get remove  kubectl 
    exit 0
    ;;
  update) 
    suto apt-get update -q
    sudo apt-mark unhold kubectl 
    sudo apt-get upgrade -y
    sudo apt-mark hold kubectl 
    exit 0
    ;;
esac
if ! _install_kubectl; then 
  echo "error kubectl install"
  exit 1
fi
