;; Only for running rebuild from within Emacs
(setq original-buffer (current-buffer))

;; Set working directory to the directory of this script
(setq working-directory (file-name-directory load-file-name))
(setq default-directory working-directory)

;; Set ~/.emacs.d/elpa path. ./.packages is relative to default-directory
(require 'package)
(setq package-user-dir (expand-file-name "./.packages"))
(setq package-archives '(("melpa" . "https://melpa.org/packages/")
                         ("elpa" . "https://elpa.gnu.org/packages/")))

;; Initialize the package system
(package-initialize)
(unless package-archive-contents
  (package-refresh-contents))

;; Install dependencies
(package-install 'ox-hugo)

;; Set Hugo directory
;; we can't use the content directory here because we'll need to rename files
;; When running hugo server, this would cause unnecessary rebuilds
(setq org-hugo-base-dir "/tmp/ox-hugo/")

;; Make sure ~key-binding~ is rendered as <kbd>key-binding</kbd> not `key-binding`
(setq org-hugo-use-code-for-kbd t)

;; Create required static folder
(make-directory (concat org-hugo-base-dir "static") :parents)

;; Delete old markdown files
(dolist (file (directory-files-recursively "content" "\\.md$"))
  (unless (file-exists-p (concat (file-name-sans-extension file) ".org"))
    (delete-file file)))

;; Generate
(dolist (file (directory-files-recursively "content" "\\.org$"))
  ;; Open file
  (find-file file)

  ;; Convert to markdown
  (org-hugo-export-wim-to-md)

  ;; Store markdown file name: path/to/file.org -> file.md
  (setq file-name (concat (file-name-sans-extension (file-name-nondirectory file)) ".md"))

  ;; Reset default-directory, it becomes the parent of the file
  (setq default-directory working-directory)

  ;; Target markdown file
  (setq target (concat (file-name-directory file) file-name))

  ;; Check if creating new file
  (setq new (not (file-exists-p target)))

  ;; Make file writable
  (unless new (set-file-modes target #o644))

  ;; Open temporary buffer
  (with-temp-buffer
    ;; Load generated markdown
    (insert-file-contents (concat org-hugo-base-dir "content/posts/" file-name))

    ;; Fix image paths: /ox-hugo/image.png -> image.png
    (while (re-search-forward "/ox-hugo/\\(.*\\)" nil t)
      (replace-match "\\1"))

    ;; Fix image formatting
    ;; Write to target unless generated markdown matches old content
    ;; It would be simpler to run file-equal-p,
    ;; but since we already have one of the files loaded that would be inefficient
    (unless (and (not new) (equal (buffer-string) (with-temp-buffer
      (insert-file-contents target)
      (buffer-string))))
      (write-region (point-min) (point-max) target nil)
    ))

  ;; Make file read-only
  (set-file-modes target #o444)

  ;; Close file unless original buffer
  (unless (eq (current-buffer) original-buffer)
    (kill-buffer)))

;; Clean up temporary directory
(delete-directory org-hugo-base-dir t)

;; Switch back to original buffer
(switch-to-buffer original-buffer)
