bb.sh 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  1. #!/usr/bin/env bash
  2. # BashBlog, a simple blog system written in a single bash script
  3. # Copyright: Carles Fenollosa <carles.fenollosa@bsc.es>, 2011-2013
  4. # With contributions from many others:
  5. # https://github.com/carlesfe/bashblog/contributors
  6. #########################################################################################
  7. #
  8. # README
  9. #
  10. #########################################################################################
  11. #
  12. # This is a very basic blog system
  13. #
  14. # Basically it asks the user to create a text file, then converts it into a .html file
  15. # and then rebuilds the index.html and feed.rss.
  16. #
  17. # Comments are supported via external service (Disqus).
  18. # Markdown syntax is supported via third party library (e.g. Gruber's Markdown.pl)
  19. #
  20. # This script is standalone, it doesn't require any other file to run
  21. #
  22. # Files that this script generates:
  23. # - main.css (inherited from my web page) and blog.css (blog-specific stylesheet)
  24. # - one .html for each post
  25. # - index.html (regenerated each run)
  26. # - feed.rss (regenerated each run)
  27. # - all_posts.html (regenerated each run)
  28. # - it also generates temporal files, which are removed afterwards
  29. #
  30. # It generates valid html and rss files, so keep care to use valid xhtml when editing a post
  31. #
  32. # There are many loops which iterate on '*.html' so make sure that the only html files
  33. # on this folder are the blog entries and index.html and all_posts.html. Drafts must go
  34. # into drafts/ and any other *.html file should be moved out of the way
  35. #
  36. # Read more: https://github.com/cfenollosa/bashblog
  37. #########################################################################################
  38. #
  39. # LICENSE
  40. #
  41. #########################################################################################
  42. #
  43. # This program is free software: you can redistribute it and/or modify
  44. # it under the terms of the GNU General Public License as published by
  45. # the Free Software Foundation, either version 3 of the License, or
  46. # (at your option) any later version.
  47. #
  48. # This program is distributed in the hope that it will be useful,
  49. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  50. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  51. # GNU General Public License for more details.
  52. #
  53. # You should have received a copy of the GNU General Public License
  54. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  55. #########################################################################################
  56. #
  57. # CHANGELOG
  58. #
  59. #########################################################################################
  60. #
  61. # 2.0 Added Markdown support
  62. # Fully support BSD date
  63. # 1.6.4 Fixed bug in localized dates
  64. # 1.6.3 Now supporting BSD date
  65. # 1.6.2 Simplified some functions and variables to avoid duplicated information
  66. # 1.6.1 'date' fix when hours are 1 digit.
  67. # 1.6.0 Disqus comments. External configuration file. Check of 'date' command version.
  68. # 1.5.1 Misc bugfixes and parameter checks
  69. # 1.5 Đurađ Radojičić (djura-san) refactored some code and added flexibility and i18n
  70. # 1.4.2 Now issues are handled at Github
  71. # 1.4.1 Some code refactoring
  72. # 1.4 Using twitter for comments, improved 'rebuild' command
  73. # 1.3 'edit' command
  74. # 1.2.2 Feedburner support
  75. # 1.2.1 Fixed the timestamps bug
  76. # 1.2 'list' command
  77. # 1.1 Draft and preview support
  78. # 1.0 Read http://is.gd/Bkdoru
  79. #########################################################################################
  80. #
  81. # CODE
  82. #
  83. #########################################################################################
  84. #
  85. # As usual with bash scripts, scroll all the way to the bottom for the main routine
  86. # All other functions are declared above main.
  87. # Global variables
  88. # It is recommended to perform a 'rebuild' after changing any of this in the code
  89. # Config file. Any settings "key=value" written there will override the
  90. # global_variables defaults. Useful to avoid editing bb.sh and having to deal
  91. # with merges in VCS
  92. global_config=".config"
  93. # This function will load all the variables defined here. They might be overriden
  94. # by the 'global_config' file contents
  95. global_variables() {
  96. global_software_name="BashBlog"
  97. global_software_version="2.0"
  98. # Blog title
  99. global_title="My fancy blog"
  100. # The typical subtitle for each blog
  101. global_description="A blog about turtles and carrots"
  102. # The public base URL for this blog
  103. global_url="http://example.com/blog"
  104. # Your name
  105. global_author="John Smith"
  106. # You can use twitter or facebook or anything for global_author_url
  107. global_author_url="http://twitter.com/example"
  108. # Your email
  109. global_email="john@smith.com"
  110. # CC by-nc-nd is a good starting point, you can change this to "&copy;" for Copyright
  111. global_license="CC by-nc-nd"
  112. # If you have a Google Analytics ID (UA-XXXXX), put it here.
  113. # If left empty (i.e. "") Analytics will be disabled
  114. global_analytics=""
  115. # Leave this empty (i.e. "") if you don't want to use feedburner,
  116. # or change it to your own URL
  117. global_feedburner=""
  118. # Change this to your username if you want to use twitter for comments
  119. global_twitter_username=""
  120. # Change this to your disqus username to use disqus for comments
  121. global_disqus_username=""
  122. # Blog generated files
  123. # index page of blog (it is usually good to use "index.html" here)
  124. index_file="index.html"
  125. number_of_index_articles="8"
  126. # global archive
  127. archive_index="all_posts.html"
  128. # feed file (rss in this case)
  129. blog_feed="feed.rss"
  130. number_of_feed_articles="10"
  131. # Localization and i18n
  132. # "Comments?" (used in twitter link after every post)
  133. template_comments="Comments?"
  134. # "View more posts" (used on bottom of index page as link to archive)
  135. template_archive="View more posts"
  136. # "Back to the index page" (used on archive page, it is link to blog index)
  137. template_archive_index_page="Back to the index page"
  138. # "Subscribe" (used on bottom of index page, it is link to RSS feed)
  139. template_subscribe="Subscribe"
  140. # "Subscribe to this page..." (used as text for browser feed button that is embedded to html)
  141. template_subscribe_browser_button="Subscribe to this page..."
  142. # "Tweet" (used as twitter text button for posting to twitter)
  143. template_twitter_button="Tweet"
  144. template_twitter_comment="&lt;Type your comment here but please leave the URL so that other people can follow the comments&gt;"
  145. # The locale to use for the dates displayed on screen (not for the timestamps)
  146. date_format="%B %d, %Y"
  147. date_locale="C"
  148. # Markdown location. Trying to autodetect by default.
  149. # The invocation must support the signature 'markdown_bin in.html > out.md'
  150. markdown_bin="$(which Markdown.pl)"
  151. }
  152. # Test if the markdown script is working correctly
  153. test_markdown() {
  154. [[ -z "$markdown_bin" ]] && return 1
  155. [[ -z "$(which diff)" ]] && return 1
  156. in="/tmp/md-in-$(echo $RANDOM).md"
  157. out="/tmp/md-out-$(echo $RANDOM).html"
  158. good="/tmp/md-good-$(echo $RANDOM).html"
  159. echo -e "line 1\n\nline 2" > $in
  160. echo -e "<p>line 1</p>\n\n<p>line 2</p>" > $good
  161. $markdown_bin $in > $out 2> /dev/null
  162. diff $good $out &> /dev/null # output is irrelevant, we'll check $?
  163. if [[ $? -ne 0 ]]; then
  164. rm -f $in $good $out
  165. return 1
  166. fi
  167. rm -f $in $good $out
  168. return 0
  169. }
  170. # Parse a Markdown file into HTML and return the generated file
  171. markdown() {
  172. out="$(echo $1 | sed 's/md$/html/g')"
  173. while [ -f "$out" ]; do out="$(echo $out | sed 's/\.html$/\.'$RANDOM'\.html')"; done
  174. $markdown_bin $1 > $out
  175. echo $out
  176. }
  177. # Prints the required google analytics code
  178. google_analytics() {
  179. [[ -z "$global_analytics" ]] && return
  180. echo "<script type=\"text/javascript\">
  181. var _gaq = _gaq || [];
  182. _gaq.push(['_setAccount', '"$global_analytics"']);
  183. _gaq.push(['_trackPageview']);
  184. (function() {
  185. var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  186. ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  187. var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  188. })();
  189. </script>"
  190. }
  191. # Prints the required code for disqus comments
  192. disqus_body() {
  193. [[ -z "$global_disqus_username" ]] && return
  194. echo '<div id="disqus_thread"></div>
  195. <script type="text/javascript">
  196. /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
  197. var disqus_shortname = '\'$global_disqus_username\''; // required: replace example with your forum shortname
  198. /* * * DONT EDIT BELOW THIS LINE * * */
  199. (function() {
  200. var dsq = document.createElement("script"); dsq.type = "text/javascript"; dsq.async = true;
  201. dsq.src = "//" + disqus_shortname + ".disqus.com/embed.js";
  202. (document.getElementsByTagName("head")[0] || document.getElementsByTagName("body")[0]).appendChild(dsq);
  203. })();
  204. </script>
  205. <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
  206. <a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>'
  207. }
  208. # Prints the required code for disqus in the footer
  209. disqus_footer() {
  210. [[ -z "$global_disqus_username" ]] && return
  211. echo '<script type="text/javascript">
  212. /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
  213. var disqus_shortname = '\'$global_disqus_username\''; // required: replace example with your forum shortname
  214. /* * * DONT EDIT BELOW THIS LINE * * */
  215. (function () {
  216. var s = document.createElement("script"); s.async = true;
  217. s.type = "text/javascript";
  218. s.src = "//" + disqus_shortname + ".disqus.com/count.js";
  219. (document.getElementsByTagName("HEAD")[0] || document.getElementsByTagName("BODY")[0]).appendChild(s);
  220. }());
  221. </script>'
  222. }
  223. # Edit an existing, published .html file while keeping its original timestamp
  224. # Please note that this function does not automatically republish anything, as
  225. # it is usually called from 'main'.
  226. #
  227. # 'edit' is kind of an advanced function, as it leaves to the user the responsibility
  228. # of editing an html file
  229. #
  230. # $1 the file to edit
  231. edit() {
  232. timestamp="$(date -r $1 +'%Y%m%d%H%M')"
  233. $EDITOR "$1"
  234. touch -t $timestamp "$1"
  235. }
  236. # Adds the code needed by the twitter button
  237. #
  238. # $1 the post URL
  239. twitter() {
  240. [[ -z "$global_twitter_username" ]] && return
  241. if [[ "$global_disqus_username" ]]; then
  242. echo "<p id='twitter'>$template_comments&nbsp;"
  243. else
  244. echo "<p id='twitter'><a href=\"$1#disqus_thread\">$template_comments</a> &nbsp;"
  245. fi
  246. echo "<a href=\"https://twitter.com/share\" class=\"twitter-share-button\" data-text=\"$template_twitter_comment\" data-url=\"$1\""
  247. echo " data-via=\"$global_twitter_username\""
  248. echo ">$template_twitter_button</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=\"//platform.twitter.com/widgets.js\";fjs.parentNode.insertBefore(js,fjs);}}(document,\"script\",\"twitter-wjs\");</script>"
  249. echo "</p>"
  250. }
  251. # Adds all the bells and whistles to format the html page
  252. # Every blog post is marked with a <!-- entry begin --> and <!-- entry end -->
  253. # which is parsed afterwards in the other functions. There is also a marker
  254. # <!-- text begin --> to determine just the beginning of the text body of the post
  255. #
  256. # $1 a file with the body of the content
  257. # $2 the output file
  258. # $3 "yes" if we want to generate the index.html,
  259. # "no" to insert new blog posts
  260. # $4 title for the html header
  261. # $5 original blog timestamp
  262. create_html_page() {
  263. content="$1"
  264. filename="$2"
  265. index="$3"
  266. title="$4"
  267. timestamp="$5"
  268. # Create the actual blog post
  269. # html, head
  270. cat ".header.html" > "$filename"
  271. echo "<title>$title</title>" >> "$filename"
  272. google_analytics >> "$filename"
  273. echo "</head><body>" >> "$filename"
  274. # body divs
  275. echo '<div id="divbodyholder">' >> "$filename"
  276. echo '<div class="headerholder"><div class="header">' >> "$filename"
  277. # blog title
  278. echo '<div id="title">' >> "$filename"
  279. cat .title.html >> "$filename"
  280. echo '</div></div></div>' >> "$filename" # title, header, headerholder
  281. echo '<div id="divbody"><div class="content">' >> "$filename"
  282. file_url="$(sed 's/.rebuilt//g' <<< $filename)" # Get the correct URL when rebuilding
  283. # one blog entry
  284. if [[ "$index" == "no" ]]; then
  285. echo '<!-- entry begin -->' >> "$filename" # marks the beginning of the whole post
  286. echo '<h3><a class="ablack" href="'$global_url/$file_url'">' >> "$filename"
  287. # remove possible <p>'s on the title because of markdown conversion
  288. echo "$(echo "$title" | sed 's/\<\/*p\>//g')" >> "$filename"
  289. echo '</a></h3>' >> "$filename"
  290. if [[ "$timestamp" == "" ]]; then
  291. echo '<div class="subtitle">'$(LC_ALL=$date_locale date +"$date_format")' &mdash; ' >> "$filename"
  292. else
  293. echo '<div class="subtitle">'$(LC_ALL=$date_locale date +"$date_format" --date="$timestamp") ' &mdash; ' >> "$filename"
  294. fi
  295. echo "$global_author</div>" >> "$filename"
  296. echo '<!-- text begin -->' >> "$filename" # This marks the text body, after the title, date...
  297. fi
  298. cat "$content" >> "$filename" # Actual content
  299. if [[ "$index" == "no" ]]; then
  300. echo '<!-- text end -->' >> "$filename"
  301. twitter "$global_url/$file_url" >> "$filename"
  302. echo '<!-- entry end -->' >> "$filename" # absolute end of the post
  303. fi
  304. echo '</div>' >> "$filename" # content
  305. # Add disqus commments except for index and all_posts pages
  306. if [[ ${filename%.*.*} != "index" && ${filename%.*.*} != "all_posts" ]]; then
  307. disqus_body >> "$filename"
  308. fi
  309. # page footer
  310. cat .footer.html >> "$filename"
  311. # close divs
  312. echo '</div></div>' >> "$filename" # divbody and divbodyholder
  313. disqus_footer >> "$filename"
  314. echo '</body></html>' >> "$filename"
  315. }
  316. # Parse the plain text file into an html file
  317. parse_file() {
  318. # Read for the title and check that the filename is ok
  319. title=""
  320. while read line; do
  321. if [[ "$title" == "" ]]; then
  322. title="$line"
  323. # remove extra <p> and </p> added by markdown
  324. filename="$(echo $title | sed 's/\<\/*p\>//g' | tr [:upper:] [:lower:])"
  325. filename="$(echo $filename | sed 's/\ /-/g')"
  326. filename="$(echo $filename | tr -dc '[:alnum:]-')" # html likes alphanumeric
  327. filename="$filename.html"
  328. content="$filename.tmp"
  329. # Check for duplicate file names
  330. while [ -f "$filename" ]; do
  331. suffix="$RANDOM"
  332. filename="$(echo $filename | sed 's/\.html/'$suffix'\.html/g')"
  333. done
  334. else
  335. echo "$line" >> "$content"
  336. fi
  337. done < "$1"
  338. # Create the actual html page
  339. create_html_page "$content" "$filename" no "$title"
  340. rm "$content"
  341. }
  342. # Manages the creation of the text file and the parsing to html file
  343. # also the drafts
  344. write_entry() {
  345. fmt="html"; f="$2"
  346. [[ "$2" == "-m" ]] && fmt="md" && f="$3"
  347. if [[ "$fmt" == "md" ]]; then
  348. test_markdown
  349. if [[ "$?" -ne 0 ]]; then
  350. echo "Markdown is not working, please use HTML. Press a key to continue..."
  351. fmt="html"
  352. read
  353. fi
  354. fi
  355. if [[ "$f" != "" ]]; then
  356. TMPFILE="$f"
  357. if [[ ! -f "$TMPFILE" ]]; then
  358. echo "The file doesn't exist"
  359. delete_includes
  360. exit
  361. fi
  362. # check if TMPFILE is markdown even though the user didn't specify it
  363. extension="${TMPFILE##*.}"
  364. [[ "$extension" == "md" ]] && fmt="md"
  365. else
  366. TMPFILE=".entry-$RANDOM.$fmt"
  367. echo "Title on this line" >> "$TMPFILE"
  368. echo "" >> "$TMPFILE"
  369. [[ "$fmt" == "html" ]] && echo -n "<p>" >> "$TMPFILE"
  370. echo -n "The rest of the text file is " >> "$TMPFILE"
  371. [[ "$fmt" == "html" ]] && echo -n "an <b>html</b> " >> "$TMPFILE"
  372. [[ "$fmt" == "md" ]] && echo -n "a **Markdown** " >> "$TMPFILE"
  373. echo -n "blog post. The process will continue as soon as you exit your editor" >> "$TMPFILE"
  374. [[ "$fmt" == "html" ]] && echo "</p>" >> "$TMPFILE"
  375. fi
  376. chmod 600 "$TMPFILE"
  377. post_status="E"
  378. while [ "$post_status" != "p" ] && [ "$post_status" != "P" ]; do
  379. $EDITOR "$TMPFILE"
  380. if [[ "$fmt" == "md" ]]; then
  381. html_from_md="$(markdown "$TMPFILE")"
  382. parse_file "$html_from_md"
  383. rm "$html_from_md"
  384. else
  385. parse_file "$TMPFILE" # this command sets $filename as the html processed file
  386. fi
  387. chmod 600 "$filename"
  388. echo -n "Preview? (Y/n) "
  389. read p
  390. if [[ "$p" != "n" ]] && [[ "$p" != "N" ]]; then
  391. chmod 644 "$filename"
  392. echo "Open $global_url/$filename in your browser"
  393. fi
  394. echo -n "[P]ost this entry, [E]dit again, [D]raft for later? (p/E/d) "
  395. read post_status
  396. if [[ "$post_status" == "d" ]] || [[ "$post_status" == "D" ]]; then
  397. mkdir -p "drafts/"
  398. chmod 700 "drafts/"
  399. title="$(head -n 1 $TMPFILE)"
  400. title="$(echo $title | tr [:upper:] [:lower:])"
  401. title="$(echo $title | sed 's/\ /-/g')"
  402. title="$(echo $title | tr -dc '[:alnum:]-')"
  403. draft="drafts/$title.$fmt"
  404. while [ -f "$draft" ]; do draft="drafts/$title-$RANDOM.$fmt"; done
  405. mv "$TMPFILE" "$draft"
  406. chmod 600 "$draft"
  407. rm "$filename"
  408. delete_includes
  409. echo "Saved your draft as '$draft'"
  410. exit
  411. fi
  412. if [[ "$post_status" == "e" ]] || [[ "$post_status" == "E" ]]; then
  413. rm "$filename" # Delete the html file as it will be generated again
  414. fi
  415. done
  416. rm "$TMPFILE"
  417. chmod 644 "$filename"
  418. echo "Posted $filename"
  419. }
  420. # Create an index page with all the posts
  421. all_posts() {
  422. echo -n "Creating an index page with all the posts "
  423. contentfile="$archive_index.$RANDOM"
  424. while [ -f "$contentfile" ]; do
  425. contentfile="$archive_index.$RANDOM"
  426. done
  427. echo "<h3>All posts</h3>" >> "$contentfile"
  428. echo "<ul>" >> "$contentfile"
  429. for i in $(ls -t *.html); do
  430. if [[ "$i" == "$index_file" ]] || [[ "$i" == "$archive_index" ]]; then continue; fi
  431. echo -n "."
  432. # Title
  433. title="$(awk '/<h3><a class="ablack" href=".+">/, /<\/a><\/h3>/{if (!/<h3><a class="ablack" href=".+">/ && !/<\/a><\/h3>/) print}' $i)"
  434. echo -n '<li><a href="'$global_url/$i'">'$title'</a> &mdash;' >> "$contentfile"
  435. # Date
  436. date="$(LC_ALL=$date_locale date -r "$i" +"$date_format")"
  437. echo " $date</li>" >> "$contentfile"
  438. done
  439. echo ""
  440. echo "</ul>" >> "$contentfile"
  441. echo '<div id="all_posts"><a href="'$global_url'">'$template_archive_index_page'</a></div>' >> "$contentfile"
  442. create_html_page "$contentfile" "$archive_index.tmp" yes "$global_title &mdash; All posts"
  443. mv "$archive_index.tmp" "$archive_index"
  444. chmod 644 "$archive_index"
  445. rm "$contentfile"
  446. }
  447. # Generate the index.html with the content of the latest posts
  448. rebuild_index() {
  449. echo -n "Rebuilding the index "
  450. newindexfile="$index_file.$RANDOM"
  451. contentfile="$newindexfile.content"
  452. while [ -f "$newindexfile" ]; do
  453. newindexfile="$index_file.$RANDOM"
  454. contentfile="$newindexfile.content"
  455. done
  456. # Create the content file
  457. n=0
  458. for i in $(ls -t *.html); do # sort by date, newest first
  459. if [[ "$i" == "$index_file" ]] || [[ "$i" == "$archive_index" ]]; then continue; fi
  460. if [[ "$n" -ge "$number_of_index_articles" ]]; then break; fi
  461. awk '/<!-- entry begin -->/, /<!-- entry end -->/' "$i" >> "$contentfile"
  462. echo -n "."
  463. n=$(( $n + 1 ))
  464. done
  465. if [[ "$global_feedburner" == "" ]]; then
  466. echo '<div id="all_posts"><a href="'$archive_index'">'$template_archive'</a> &mdash; <a href="'$blog_feed'">'$template_subscribe'</a></div>' >> "$contentfile"
  467. else
  468. echo '<div id="all_posts"><a href="'$archive_index'">'$template_archive'</a> &mdash; <a href="'$global_feedburner'">Subscribe</a></div>' >> "$contentfile"
  469. fi
  470. echo ""
  471. create_html_page "$contentfile" "$newindexfile" yes "$global_title"
  472. rm "$contentfile"
  473. mv "$newindexfile" "$index_file"
  474. chmod 644 "$index_file"
  475. }
  476. # Displays a list of the posts
  477. list_posts() {
  478. ls *.html &> /dev/null
  479. [[ $? -ne 0 ]] && echo "No posts yet. Use 'bb.sh post' to create one" && return
  480. lines=""
  481. n=1
  482. for i in $(ls -t *.html); do
  483. if [[ "$i" == "$index_file" ]] || [[ "$i" == "$archive_index" ]]; then continue; fi
  484. line="$n # $(awk '/<h3><a class="ablack" href=".+">/, /<\/a><\/h3>/{if (!/<h3><a class="ablack" href=".+">/ && !/<\/a><\/h3>/) print}' $i) # $(LC_ALL=$date_locale date -r $i +"date_format")"
  485. lines="${lines}""$line""\n" # Weird stuff needed for the newlines
  486. n=$(( $n + 1 ))
  487. done
  488. echo -e "$lines" | column -t -s "#"
  489. }
  490. # Generate the feed file
  491. make_rss() {
  492. echo -n "Making RSS "
  493. rssfile="$blog_feed.$RANDOM"
  494. while [ -f "$rssfile" ]; do rssfile="$blog_feed.$RANDOM"; done
  495. echo '<?xml version="1.0" encoding="UTF-8" ?>' >> "$rssfile"
  496. echo '<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">' >> "$rssfile"
  497. echo '<channel><title>'$global_title'</title><link>'$global_url'</link>' >> "$rssfile"
  498. echo '<description>'$global_description'</description><language>en</language>' >> "$rssfile"
  499. echo '<lastBuildDate>'$(date +"%a, %d %b %Y %H:%M:%S %z")'</lastBuildDate>' >> "$rssfile"
  500. echo '<pubDate>'$(date +"%a, %d %b %Y %H:%M:%S %z")'</pubDate>' >> "$rssfile"
  501. echo '<atom:link href="'$global_url/$blog_feed'" rel="self" type="application/rss+xml" />' >> "$rssfile"
  502. n=0
  503. for i in $(ls -t *.html); do
  504. if [[ "$i" == "$index_file" ]] || [[ "$i" == "$archive_index" ]]; then continue; fi
  505. [[ "$n" -ge "$number_of_feed_articles" ]] && break # max 10 items
  506. echo -n "."
  507. echo '<item><title>' >> "$rssfile"
  508. echo "$(awk '/<h3><a class="ablack" href=".+">/, /<\/a><\/h3>/{if (!/<h3><a class="ablack" href=".+">/ && !/<\/a><\/h3>/) print}' $i)" >> "$rssfile"
  509. echo '</title><description><![CDATA[' >> "$rssfile"
  510. echo "$(awk '/<!-- text begin -->/, /<!-- entry end -->/{if (!/<!-- text begin -->/ && !/<!-- entry end -->/) print}' $i)" >> "$rssfile"
  511. echo "]]></description><link>$global_url/$i</link>" >> "$rssfile"
  512. echo "<guid>$global_url/$i</guid>" >> "$rssfile"
  513. echo "<dc:creator>$global_author</dc:creator>" >> "$rssfile"
  514. echo '<pubDate>'$(date -r "$i" +"%a, %d %b %Y %H:%M:%S %z")'</pubDate></item>' >> "$rssfile"
  515. n=$(( $n + 1 ))
  516. done
  517. echo '</channel></rss>' >> "$rssfile"
  518. echo ""
  519. mv "$rssfile" "$blog_feed"
  520. chmod 644 "$blog_feed"
  521. }
  522. # generate headers, footers, etc
  523. create_includes() {
  524. echo '<h1 class="nomargin"><a class="ablack" href="'$global_url'">'$global_title'</a></h1>' > ".title.html"
  525. echo '<div id="description">'$global_description'</div>' >> ".title.html"
  526. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' > ".header.html"
  527. echo '<html xmlns="http://www.w3.org/1999/xhtml"><head>' >> ".header.html"
  528. echo '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />' >> ".header.html"
  529. echo '<link rel="stylesheet" href="main.css" type="text/css" />' >> ".header.html"
  530. echo '<link rel="stylesheet" href="blog.css" type="text/css" />' >> ".header.html"
  531. if [[ "$global_feedburner" == "" ]]; then
  532. echo '<link rel="alternate" type="application/rss+xml" title="'$template_subscribe_browser_button'" href="'$blog_feed'" />' >> ".header.html"
  533. else
  534. echo '<link rel="alternate" type="application/rss+xml" title="'$template_subscribe_browser_button'" href="'$global_feedburner'" />' >> ".header.html"
  535. fi
  536. protected_mail="$(echo "$global_email" | sed 's/@/\&#64;/g' | sed 's/\./\&#46;/g')"
  537. echo '<div id="footer">'$global_license '<a href="'$global_author_url'">'$global_author'</a> &mdash; <a href="mailto:'$protected_mail'">'$protected_mail'</a></div>' >> ".footer.html"
  538. }
  539. # Delete the temporarily generated include files
  540. delete_includes() {
  541. rm ".title.html" ".footer.html" ".header.html"
  542. }
  543. # Create the css file from scratch
  544. create_css() {
  545. # To avoid overwriting manual changes. However it is recommended that
  546. # this function is modified if the user changes the blog.css file
  547. if [[ ! -f "blog.css" ]]; then
  548. # blog.css directives will be loaded after main.css and thus will prevail
  549. echo '#title{font-size: x-large;}
  550. a.ablack{color:black !important;}
  551. li{margin-bottom:8px;}
  552. ul,ol{margin-left:24px;margin-right:24px;}
  553. #all_posts{margin-top:24px;text-align:center;}
  554. .subtitle{font-size:small;margin:12px 0px;}
  555. .content p{margin-left:24px;margin-right:24px;}
  556. h1{margin-bottom:12px !important;}
  557. #description{font-size:large;margin-bottom:12px;}
  558. h3{margin-top:42px;margin-bottom:8px;}
  559. h4{margin-left:24px;margin-right:24px;}
  560. #twitter{line-height:20px;vertical-align:top;text-align:right;font-style:italic;color:#333;margin-top:24px;font-size:14px;}' > blog.css
  561. fi
  562. # If there is a style.css from the parent page (i.e. some landing page)
  563. # then use it. This directive is here for compatibility with my own
  564. # home page. Feel free to edit it out, though it doesn't hurt
  565. if [[ -f "../style.css" ]] && [[ ! -f "main.css" ]]; then
  566. ln -s "../style.css" "main.css"
  567. elif [[ ! -f "main.css" ]]; then
  568. echo 'body{font-family:Georgia,"Times New Roman",Times,serif;margin:0;padding:0;background-color:#F3F3F3;}
  569. #divbodyholder{padding:5px;background-color:#DDD;width:874px;margin:24px auto;}
  570. #divbody{width:776px;border:solid 1px #ccc;background-color:#fff;padding:0px 48px 24px 48px;top:0;}
  571. .headerholder{background-color:#f9f9f9;border-top:solid 1px #ccc;border-left:solid 1px #ccc;border-right:solid 1px #ccc;}
  572. .header{width:800px;margin:0px auto;padding-top:24px;padding-bottom:8px;}
  573. .content{margin-bottom:45px;}
  574. .nomargin{margin:0;}
  575. .description{margin-top:10px;border-top:solid 1px #666;padding:10px 0;}
  576. h3{font-size:20pt;width:100%;font-weight:bold;margin-top:32px;margin-bottom:0;}
  577. .clear{clear:both;}
  578. #footer{padding-top:10px;border-top:solid 1px #666;color:#333333;text-align:center;font-size:small;font-family:"Courier New","Courier",monospace;}
  579. a{text-decoration:none;color:#003366 !important;}
  580. a:visited{text-decoration:none;color:#336699 !important;}
  581. blockquote{background-color:#f9f9f9;border-left:solid 4px #e9e9e9;margin-left:12px;padding:12px 12px 12px 24px;}
  582. blockquote img{margin:12px 0px;}
  583. blockquote iframe{margin:12px 0px;}' > main.css
  584. fi
  585. }
  586. # Regenerates all the single post entries, keeping the post content but modifying
  587. # the title, html structure, etc
  588. rebuild_all_entries() {
  589. echo -n "Rebuilding all entries "
  590. for i in *.html; do # no need to sort
  591. if [[ "$i" == "$index_file" ]] || [[ "$i" == "$archive_index" ]]; then continue; fi
  592. contentfile=".tmp.$RANDOM"
  593. while [ -f "$contentfile" ]; do contentfile=".tmp.$RANDOM"; done
  594. echo -n "."
  595. # Get the title and entry, and rebuild the html structure from scratch (divs, title, description...)
  596. title="$(awk '/<h3><a class="ablack" href=".+">/, /<\/a><\/h3>/{if (!/<h3><a class="ablack" href=".+">/ && !/<\/a><\/h3>/) print}' $i)"
  597. awk '/<!-- text begin -->/, /<!-- text end -->/{if (!/<!-- text begin -->/ && !/<!-- text end -->/) print}' "$i" >> "$contentfile"
  598. # Original post timestamp
  599. timestamp="$(date -r $i +"%a, %d %b %Y %H:%M:%S %z" )"
  600. create_html_page "$contentfile" "$i.rebuilt" no "$title" "$timestamp"
  601. # keep the original timestamp!
  602. timestamp="$(date -r $i +'%Y%m%d%H%M')"
  603. mv "$i.rebuilt" "$i"
  604. chmod 644 "$i"
  605. touch -t $timestamp "$i"
  606. rm "$contentfile"
  607. done
  608. echo ""
  609. }
  610. # Displays the help
  611. function usage() {
  612. echo "$global_software_name v$global_software_version"
  613. echo "Usage: $0 command [filename]"
  614. echo ""
  615. echo "Commands:"
  616. echo " post [-m] [filename] insert a new blog post, or the FILENAME of a draft to continue editing it"
  617. echo " use '-m' to edit the post as Markdown text"
  618. echo " edit [filename] edit an already published .html file. Never edit manually a published .html file,"
  619. echo " always use this function as it keeps the original timestamp "
  620. echo " and rebuilds whatever indices are needed"
  621. echo " rebuild regenerates all the pages and posts, preserving the content of the entries"
  622. echo " reset deletes blog-generated files. Use with a lot of caution and back up first!"
  623. echo " list list all entries. Useful for debug"
  624. echo ""
  625. echo "For more information please open $0 in a code editor and read the header and comments"
  626. }
  627. # Delete all generated content, leaving only this script
  628. reset() {
  629. echo "Are you sure you want to delete all blog entries? Please write \"Yes, I am!\" "
  630. read line
  631. if [[ "$line" == "Yes, I am!" ]]; then
  632. rm .*.html *.html *.css *.rss &> /dev/null
  633. echo
  634. echo "Deleted all posts, stylesheets and feeds."
  635. echo "Kept your old '.backup.tar.gz' just in case, please delete it manually if needed."
  636. else
  637. echo "Phew! You dodged a bullet there. Nothing was modified."
  638. fi
  639. }
  640. # Detects if GNU date is installed
  641. date_version_detect() {
  642. date --version >/dev/null 2>&1
  643. if [[ $? -ne 0 ]]; then
  644. # date utility is BSD. Test if gdate is installed
  645. if gdate --version >/dev/null 2>&1 ; then
  646. date() {
  647. gdate "$@"
  648. }
  649. else
  650. # BSD date
  651. date() {
  652. if [[ "$1" == "-r" ]]; then
  653. # Fall back to using stat for 'date -r'
  654. format=$(echo $3 | sed 's/\+//g')
  655. stat -f "%Sm" -t "$format" "$2"
  656. elif [[ $(echo $@ | grep '\-\-date') ]]; then
  657. # convert between dates using BSD date syntax
  658. /bin/date -j -f "%a, %d %b %Y %H:%M:%S %z" "$(echo $3 | sed 's/\-\-date\=//g')" "$2"
  659. else
  660. # acceptable format for BSD date
  661. /bin/date -j "$@"
  662. fi
  663. }
  664. fi
  665. fi
  666. }
  667. # Main function
  668. # Encapsulated on its own function for readability purposes
  669. #
  670. # $1 command to run
  671. # $2 file name of a draft to continue editing (optional)
  672. do_main() {
  673. # Detect if using BSD date or GNU date
  674. date_version_detect
  675. # Load default configuration, then override settings with the config file
  676. global_variables
  677. [[ -f "$global_config" ]] && source "$global_config" &> /dev/null
  678. # Check for $EDITOR
  679. [[ -z "$EDITOR" ]] &&
  680. echo "Please set your \$EDITOR environment variable" && exit
  681. # Check for validity of argument
  682. [[ "$1" != "reset" ]] && [[ "$1" != "post" ]] && [[ "$1" != "rebuild" ]] && [[ "$1" != "list" ]] && [[ "$1" != "edit" ]] &&
  683. usage && exit
  684. [[ "$1" == "list" ]] &&
  685. list_posts && exit
  686. if [[ "$1" == "edit" ]]; then
  687. if [[ $# -lt 2 ]] || [[ ! -f "$2" ]]; then
  688. echo "Please enter a valid html file to edit"
  689. exit
  690. fi
  691. fi
  692. # Test for existing html files
  693. ls *.html &> /dev/null
  694. [[ $? -ne 0 ]] && [[ "$1" == "rebuild" ]] &&
  695. echo "Can't find any html files, nothing to rebuild" && exit
  696. # We're going to back up just in case
  697. ls *.html &> /dev/null
  698. [[ $? -eq 0 ]] &&
  699. tar cfz ".backup.tar.gz" *.html &&
  700. chmod 600 ".backup.tar.gz"
  701. [[ "$1" == "reset" ]] &&
  702. reset && exit
  703. create_includes
  704. create_css
  705. [[ "$1" == "post" ]] && write_entry "$@"
  706. [[ "$1" == "rebuild" ]] && rebuild_all_entries
  707. [[ "$1" == "edit" ]] && edit "$2"
  708. rebuild_index
  709. all_posts
  710. make_rss
  711. delete_includes
  712. }
  713. #
  714. # MAIN
  715. # Do not change anything here. If you want to modify the code, edit do_main()
  716. #
  717. do_main $*