#!/bin/bash


ACTION="$1"


case $ACTION in

	postInstall)

		# just in case something failed. we need a fresh start
		rm -rf /opt/openvino-models
		rm -rf /usr/lib/openvino-models
		rm -rf /var/snap/audacity/common/tmp
		rm -rf /var/snap/audacity/common/models/openvino-models
		
		RC=1
		dpkg -s audacity-ai 1>/dev/null 2>/dev/null|| RC=0

		# Restore current audacity
		if [ $RC = 1 ]; then
                	OLD_AUDACITY=$(LANG=C apt policy audacity | grep Cand | cut -d ":" -f 2 | xargs)
                	if [ -z $OLD_AUDACITY ];then
                	        echo "Error: Failed to query stable audacity version."
                	        exit 1

               		 fi
			 apt install -y audacity-data=$OLD_AUDACITY audacity=$OLD_AUDACITY
		fi

		# fetch all models
		audacity.fetch-models -v -b 

		# connect snap to alsa
		snap connect audacity:alsa

		# looks like we need to restart namespace mounts or else we need a system restart for models to be seen inside snap mounts
		/usr/lib/snapd/snap-discard-ns audacity || true

		# hide audacity-deb
		mv /usr/share/applications/audacity.desktop /usr/share/applications/audacity.desktop.snap_diverted


	;;	

	remove)
	
                RC=1
                dpkg -s audacity-ai 1>/dev/null 2>/dev/null|| RC=0

                # Restore current audacity
                if [ $RC = 1 ]; then
                        OLD_AUDACITY=$(LANG=C apt policy audacity | grep Cand | cut -d ":" -f 2 | xargs)
                        if [ -z $OLD_AUDACITY ];then
                                echo "Error: Failed to query stable audacity version."
                                exit 1
                      
                         fi
                         apt install -y audacity-data=$OLD_AUDACITY audacity=$OLD_AUDACITY
		fi

		snap remove audacity --purge
		TEST=$(snap list | grep audacity | cut -d " " -f 1)
		if [[ ! -z "$TEST" ]];then
                	exit 1

		fi


		if [ -e /usr/share/applications/audacity.desktop.snap_diverted ];then
			mv /usr/share/applications/audacity.desktop.snap_diverted /usr/share/applications/audacity.desktop
		fi

		if [ -e /var/snap/audacity/common/models/openvino-models ];then
			rm -rf /var/snap/audacity/common/models/openvino-models
		fi



	;;	

esac
exit 0
