(require 'common-lsp)
(require 'util-tree-sitter)

(defun terraform-fmt ()
  "Run terraform fmt."
  (run-command-on-buffer "terraform" "fmt" "-")
  )


(use-package hcl-mode
  :mode (("\\.hcl\\'" . hcl-mode))
  :commands hcl-mode
  :custom (hcl-indent-level 2)
  :hook (
         (hcl-mode . (lambda () (unless (derived-mode-p 'terraform-mode) (add-hook 'before-save-hook 'terraform-fmt nil 'local))))
         )
  )

(use-package terraform-mode
  :mode (("\\.tf\\'" . terraform-mode)
         ("\\.tfvars\\'" . terraform-mode))
  :commands terraform-mode
  :custom (terraform-indent-level 2)
  :hook (
         (terraform-mode . (lambda ()
                             (eglot-ensure)
                             (defclass my/eglot-terraform (eglot-lsp-server) ()
                               :documentation
                               "Own eglot server class.")

                             (add-to-list 'eglot-server-programs
                                          '(terraform-mode . (my/eglot-terraform "terraform-ls" "serve")))
                             (add-hook 'before-save-hook 'eglot-format-buffer nil 'local)
                             ))
         )
  )

(provide 'lang-terraform)
