#!/usr/bin/env bash
set -e


# Bootstrap
set -e
ROOT_FOLDER=$(realpath $0 | xargs dirname | xargs dirname)
. $ROOT_FOLDER/bin/extra/common.sh
# Bootstrap

pushd $ROOT_FOLDER > /dev/null

tfvar_file=$ROOT_FOLDER/var.auto.tfvars
tfvar_ns=default
kubectl config use-context homelab

function run-new-chart() {
    : Create a new helm chart
    : dev new-chart {path-to-chart}
    
    full_path=$ROOT_FOLDER/apps${1}
    app=$(basename $full_path)
    location=$(dirname $full_path)
    typeofapp=$(basename $location)
    
    mkdir -p $full_path/templates
    touch $full_path/values.yaml
    cat <<EOT >> $full_path/Chart.yaml
apiVersion: v2
name: $app
description: An $typeofapp service for homelab
type: application
version: 0.1.0
dependencies: []
EOT
}

function run-upload-tfvars() {
    : Uploads tfvars to k8s cluster
    : dev upload-tfvars
    kubectl -n $tfvar_ns create secret generic tfvars \
    --dry-run=client \
    --save-config \
    --from-file=tfvars=$tfvar_file \
    -o yaml | \
    kubectl -n $tfvar_ns apply -f -
}

function run-download-tfvars() {
    : Download tfvars from k8s cluster
    : dev download-tfvars
    kubectl -n $tfvar_ns get secrets/tfvars -o jsonpath='{.data.tfvars}' | base64 -d > $tfvar_file
}

function run-template() {
    :
    :
    app_name=${1}
    tmp_folder=$ROOT_FOLDER/.tmp/homelab/tpl-$app_name
    rm -rf $tmp_folder
    mkdir -p $tmp_folder
    kubectl get -n plugin-argo-cd applications.argoproj.io $app_name -o jsonpath='{.spec.source}' > $tmp_folder/spec.json
    folder=$(cat $tmp_folder/spec.json | jq -r '.path')
    cat $tmp_folder/spec.json | jq -r '.helm.values' > $tmp_folder/v.yaml
    valuesFiles="--values "$(cat $tmp_folder/spec.json | jq -r '.helm.valueFiles | join(" --values ")')
    pushd $ROOT_FOLDER/$folder &> /dev/null
    hcmd="helm template --debug $valuesFiles --values $tmp_folder/v.yaml ."
    echo $hcmd
    $hcmd > $tmp_folder/rendered.yaml
    cat $tmp_folder/rendered.yaml
    echo $tmp_folder/rendered.yaml
    popd &> /dev/null
}

start_cli $@