Fix deploy as is VM start after template deletion (#8115)

diff --git a/server/src/main/java/com/cloud/template/HypervisorTemplateAdapter.java b/server/src/main/java/com/cloud/template/HypervisorTemplateAdapter.java
index cdd58ce..1633cd8 100644
--- a/server/src/main/java/com/cloud/template/HypervisorTemplateAdapter.java
+++ b/server/src/main/java/com/cloud/template/HypervisorTemplateAdapter.java
@@ -29,6 +29,8 @@
 import javax.inject.Inject;
 
 import com.cloud.domain.Domain;
+import com.cloud.vm.VMInstanceVO;
+import com.cloud.vm.dao.VMInstanceDao;
 import org.apache.cloudstack.agent.directdownload.CheckUrlAnswer;
 import org.apache.cloudstack.agent.directdownload.CheckUrlCommand;
 import org.apache.cloudstack.annotation.AnnotationService;
@@ -142,6 +144,8 @@
     private TemplateDeployAsIsDetailsDao templateDeployAsIsDetailsDao;
     @Inject
     private AnnotationDao annotationDao;
+    @Inject
+    VMInstanceDao _vmInstanceDao;
 
     @Override
     public String getName() {
@@ -662,11 +666,7 @@
             Pair<Class<?>, Long> tmplt = new Pair<Class<?>, Long>(VirtualMachineTemplate.class, template.getId());
             _messageBus.publish(_name, EntityManager.MESSAGE_REMOVE_ENTITY_EVENT, PublishScope.LOCAL, tmplt);
 
-            // Remove template details
-            templateDetailsDao.removeDetails(template.getId());
-
-            // Remove deploy-as-is details (if any)
-            templateDeployAsIsDetailsDao.removeDetails(template.getId());
+            checkAndRemoveTemplateDetails(template);
 
             // Remove comments (if any)
             AnnotationService.EntityType entityType = template.getFormat().equals(ImageFormat.ISO) ?
@@ -677,6 +677,23 @@
         return success;
     }
 
+    /**
+     * removes details of the template and
+     * if the template is registered as deploy as is,
+     * then it also deletes the details related to deploy as is only if there are no VMs using the template
+     * @param template
+     */
+    void checkAndRemoveTemplateDetails(VMTemplateVO template) {
+        templateDetailsDao.removeDetails(template.getId());
+
+        if (template.isDeployAsIs()) {
+            List<VMInstanceVO> vmInstanceVOList = _vmInstanceDao.listNonExpungedByTemplate(template.getId());
+            if (CollectionUtils.isEmpty(vmInstanceVOList)) {
+                templateDeployAsIsDetailsDao.removeDetails(template.getId());
+            }
+        }
+    }
+
     @Override
     public TemplateProfile prepareDelete(DeleteTemplateCmd cmd) {
         TemplateProfile profile = super.prepareDelete(cmd);