#!/usr/bin/bash

###########
# functions
###########
ask_to_proceed() {
        read -p "*** $1 (Y|n): " answer
        if [[ "${answer}" != "y"  ]] && [[ "${answer}" != "Y"  ]] && [[ "${answer}" != ""  ]]; then
                exit;
        fi
}

###########
# script
###########
echo "This script installs the software to run Smartfacts in an air gapped environment. Please make sure that all files are downloaded befor running this script. For more information see https://smartfacts.atlassian.net/wiki/spaces/SPD/pages/18448385/Deployment+on+Kubernetes+without+Internet+Connection."
ask_to_proceed "Install software?"

## check if all files are present
echo "Checking if all files are present..."
filenames=("k3s" "helm-v*-linux-amd64.tar.gz" "k3s-airgap-images-amd64.tar.gz" "install.sh")
for f in ${filenames[@]}; do
        if [ ! -f $f ]; then
                echo "File \"$f\" not found. Please download it and copy it into the directory $(pwd)"
        fi
done

# k3s
echo "Installing k3s..."
sudo mkdir -p /var/lib/rancher/k3s/agent/images/
gzip -d k3s-airgap-images-amd64.tar.gz
sudo mv k3s-airgap-images-amd64.tar /var/lib/rancher/k3s/agent/images/
sudo cp k3s /usr/local/bin
sudo chmod +x /usr/local/bin/k3s
chmod +x install.sh
INSTALL_K3S_SKIP_DOWNLOAD=true ./install.sh
sudo mkdir -p /root/.kube/
sudo cp /etc/rancher/k3s/k3s.yaml /root/.kube/config
echo "k3s installed."

# HELM
echo "Installing helm..."
tar -zxvf helm-*-linux-amd64.tar.gz
sudo mv linux-amd64/helm /usr/local/bin/helm
rm -r linux-amd64
echo "helm installed."
echo "*** FINISHED ***"