#!/usr/bin/bash
# To be used by client with the command:
#   sh -x <(curl https://ftp.eso.org/pub/vlt/repos/GetPlatform.sh)
# or
#   sh -x <(curl https://ftp.eso.org/pub/vlt/repos/GetPlatform.sh) <release>

set -e

# Determine default platform version
vltswver=$(
  source /etc/os-release
  if [[ ${ID} == almalinux ]] && [[ ${VERSION_ID} == 10.* ]]; then
    echo vlt2026.latest
  fi
)
while [ -n "$1" ]; do
  case $1 in
    *) vltswver=$1
      shift ;;
  esac
done

if [[ -z ${vltswver} ]]; then
  echo "VLT Platform version is not defined"
  exit 1
fi

RPMNAME="vlt-vltsw-ansible"
SCRIPTNAME="ansible-force-align"

if rpm -q ${RPMNAME} >/dev/null 2>&1 ; then
 echo "RPM ${RPMNAME} already installed"
 exit 0
fi

# ELTDEV-1156
MINSIZE=20
size_root=`/usr/bin/df -H / | tail -1 | gawk '{print $2}' | sed 's/G//'`
if [ $size_root -le $MINSIZE ]; then
  echo ""
  echo "WARNING: The root partition might not big enough (>${MINSIZE}G):"
  df -H /
  freesize=`vgs | tail -1 | gawk '{print $7}'`
  if [ "$freesize" !=  "0" ]; then
    vgs
    echo ""
    echo "Some free disk space still available for the root partition"
    echo "You may extend it, as root, with the command:"
    echo "  lvextend /dev/mapper/fedora_fedora-root -l100%FREE"
    echo "  xfs_growfs /dev/mapper/fedora_fedora-root"
  fi
  echo ""
  echo -n "Do you want to continue [yn] (n)? : "
  read answ
  if [ -z "$answ" -o "$answ" != "y" ]; then
    exit 0
  fi
fi

# VLT platform repo
platformrepo=$(
  if [[ ${vltswver} == vlt2026.* ]]; then
    echo https://ftp.eso.org/pub/vlt/repos/eso/platform/26/${vltswver}
  fi
)

#TMP TESTING
platformrepo="http://obs.hq.eso.org:82/vlt:/vltsw:/2026/vlt_almalinux_10/"
#TMP

# Check the platform repository exists:
if `curl ${platformrepo} 2>/dev/null | grep -q "was not found"`
then
  echo "ERROR. Cannot find repository ${platform_repo}"
  exit 1
fi

echo ${platformrepo}


dnf clean all
dnf -y --nogpgcheck --disablerepo="*" --repofrompath vltplatform,${platformrepo} install vlt-vltsw-repos

if [ $? -ne 0 ]; then
  echo "Download of RPM vlt-devenv-repos failed"
  exit 1
fi


echo $vltswver > /etc/dnf/vars/vltswver

#TMP TESTING
dnf config-manager --set-enabled vlt-vltsw-obs
#TMP

dnf -y install ${RPMNAME}

cd /root/vlt
echo "Executing: ${SCRIPTNAME}"
./${SCRIPTNAME}

exit $?
