#!/bin/bash
# Info: Script to install nfs packages
# Author: JesusPerezLorenzo  
# Release: 1.1
# Date: 8-07-2024

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

_add_nfs_server() {
    chmod 1777 /tmp
    echo 'debconf debconf/frontend select Noninteractive' | sudo debconf-set-selections
    DEBIAN_FRONTEND=noninteractive sudo apt-get -y -qq install sudo nfs-server
}

# Update and add packages to installation
[ -z "$(type -P exporfs)" ] && _add_nfs_server

[ -r "env-external-nfs" ] && .  env-external-nfs  

WORK_PATH=${WORK_PATH:-/tmp}

if [ -z "$NFS_IP" ] || [ -z "$NFS_NET" ] || [ -z "$NFS_SHARE_PATH" ] ; then 
   echo "Error: IP  NET SHARE_PATH not all set for NFS" 
   exit 1
fi
[ ! -d "$NFS_SHARE_PATH" ] && mkdir -p "$NFS_SHARE_PATH" && chmod 777 "$NFS_SHARE_PATH"
if ! grep -q "$NFS_NET" /etc/exports ; then 
   [ -r "exports" ] && cat exports | sudo tee -a /etc/exports && exportfs -a 
fi
if [ -r "/etc/kubernetes/manifests/kube-apiserver.yaml"  ] ; then 
   has_kubectl=$(type -P kubectl 2>/dev/null)
   [ -z "$has_kubectl" ] &&  echo "kubectl command not found"  && exit 0
   if kubectl apply -f core-nfs.yaml && kubectl apply -f storage-class.yaml ; then 
      [ -r "deploy-external-nfs.yaml" ] && kubectl apply -f deploy-external-nfs.yaml
      [ "$WORK_PATH" != "/tmp" ] && {
         sudo mkdir -p "$WORK_PATH/external-nfs"
         sudo mv core-nfs.yaml stroge-class.yaml deploy-external-nfs.yaml "$WORK_PATH/external-nfs"
      }
      exit 0
   else
      echo "Error kubectl install errors " && exit 1
   fi
fi

