#!/bin/bash

DIR="$(dirname "$(realpath "$0")")"
CURA_CONFIG_BASE="${HOME}/.config/cura"
CURA_FOLDER="/opt/ultimaker-cura"

function get_cura_directories() {
	local VERSION
	VERSION=$(find "${CURA_CONFIG_BASE}" -maxdepth 1 -mindepth 1 -type d -printf "%f\n" -prune | sort -gr | head -n1)
	CURA_CONFIG="${HOME}/.config/cura/${VERSION}"
	CURA_SHARE="${HOME}/.local/share/cura/${VERSION}"
	CURA_INTERNAL_SHARE="${CURA_FOLDER}/share/cura/resources"
}

get_cura_directories

echo "-------------------"
echo "Cura Configuration Folder: ${CURA_CONFIG}"
echo "Cura Share Folder: ${CURA_SHARE}"
echo "Cura Folder: ${CURA_FOLDER}"
echo "Own Folder: ${DIR}"
echo "-------------------"
echo "Deleting existing Cura resources for the printer FLSUN V400"
find "${CURA_INTERNAL_SHARE}" -type f -iname 'flsun_v400*' -exec sudo rm {} +
echo "-------------------"
echo "Installing new Cura resources for the printer FLSUN V400"
mkdir -p "${CURA_SHARE}/definitions" 2>/dev/null
mkdir -p "${CURA_SHARE}/extruders" 2>/dev/null
mkdir -p "${CURA_SHARE}/meshes" 2>/dev/null
ln -sf "${DIR}/definitions/flsun_v400.def.json" "${CURA_SHARE}/definitions/flsun_v400.def.json"
ln -sf "${DIR}/extruders/flsun_v400_extruder_0.def.json" "${CURA_SHARE}/extruders/flsun_v400_extruder_0.def.json"
ln -sf "${DIR}/meshes/flsun_v400.stl" "${CURA_SHARE}/meshes/flsun_v400.stl"
echo "-------------------"
echo "Installing Quality Profile"
mkdir -p "${CURA_SHARE}/quality"
mkdir -p "${CURA_SHARE}/quality/PLA/0.4"
mkdir -p "${CURA_SHARE}/variants"
ln -sf "${DIR}/quality/flsun_v400_global_Draft_Quality.inst.cfg" "${CURA_SHARE}/quality/flsun_v400_global_Draft_Quality.inst.cfg"
ln -sf "${DIR}/variants/flsun_v400_0.4.inst.cfg" "${CURA_SHARE}/variants/flsun_v400_0.4.inst.cfg"
ln -sf "${DIR}/quality/PLA/0.4/flsun_v400_0.4_PLA_Draft_Print.inst.cfg" "${CURA_SHARE}/quality/PLA/0.4/flsun_v400_0.4_PLA_Draft_Print.inst.cfg"
echo "-------------------"
echo "Done"
