~stormdragon2976/bashtml

a4343207b19138cd44f928869027d6cd8e433022 — Storm Dragon 1 year, 5 days ago 3f5863f
Initial commit of new code base. This is now officially a fork of bashblog.
5 files changed, 2040 insertions(+), 644 deletions(-)

D .gitmodules
M LICENSE
M README.md
D bashtml-plugins
M bashtml.sh
D .gitmodules => .gitmodules +0 -3
@@ 1,3 0,0 @@
[submodule "bashtml-plugins"]
	path = bashtml-plugins
	url = https://gitlab.com/stormdragon2976/bashtml-plugins.git

M LICENSE => LICENSE +674 -14
@@ 1,14 1,674 @@
            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
                    Version 2, December 2004

 Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>

 Everyone is permitted to copy and distribute verbatim or modified
 copies of this license document, and changing it is allowed as long
 as the name is changed.

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. You just DO WHAT THE FUCK YOU WANT TO.

                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

M README.md => README.md +174 -30
@@ 1,52 1,196 @@
# bashtml
bashblog
========

A single Bash script to create blogs. 

A bash script to create static html blog. Inspired by [bashblog](https://github.com/cfenollosa/bashblog).
I created it because I wanted a very, very simple way to post entries to a blog by using a public folder on my server, without any special requirements and dependencies. Works on GNU/Linux, OSX and BSD.

*How simple? Just type `./bb.sh post` and start writing your blogpost.*

## Getting Started
[![asciinema](https://asciinema.org/a/4nr44km9ipow4s7u2w2eabeik.png)](https://asciinema.org/a/4nr44km9ipow4s7u2w2eabeik)

You can see a sample here: [read the initial blog post](https://web.archive.org/web/20130520204024/http://mmb.pcb.ub.es/~carlesfe/blog/creating-a-simple-blog-system-with-a-500-line-bash-script.html). That page was 100% generated using bashblog, no additional tweaking.

Create the directory where you want your site:
[![demo](https://raw.githubusercontent.com/cfenollosa/bashblog/gh-pages/images/demo_thumb.png)](https://raw.githubusercontent.com/cfenollosa/bashblog/gh-pages/images/demo.png)

Check out [other bashblog users](https://www.google.com/search?q=%22Generated+with+bashblog,+a+single+bash+script+to+easily+create+blogs+like+this+one%22)

    mkdir mysite
    cd mysite

Usage
-----

Run bashtml with no arguments to generate the configuration file, called .bashtmlrc. After the file has been created, edit it and change the information to personalize your site.
Download the code and copy bb.sh into a public folder (for example, `$HOME/public_html/blog`) and run

    ./bb.sh

## Options
This will show the available commands. If the file is not executable, type `chmod +x bb.sh` and retry.

**Before creating your first post, you may want to configure the blog settings (title, author, etc).
Read the Configuration section below for more information**

The following options are available.
To create your first post, just run:

    ./bb.sh post
    
It will try to use Markdown, if installed. To force HTML:

- -h, --help: A brief help message.
- -n, -p, --post: Create a new post.
- -r, --rebuild: Rebuild the site. Requires the markdown files.
- -s, --sync: Sync your local copy of the site to the server, requires the rsync section of the configuration file be set.
    ./bb.sh post -html
    
The script will handle the rest.

When you're done, access the public URL for that folder  (e.g. `http://server.com/~username/blog`) 
and you should see the index file and a new page for that post!

## Plugins

Features
--------

Plugins extend the functionality of bashtml. Some plugins are available from the [bashtml-plugins project](https://gitlab.com/stormdragon2976/bashtml-plugins). In your site directory, create a  directory called bashtml-plugins. Place the plugin you want to use in the bashtml-plugins directory. The last part of the file name determines the type of plugin. For example, the name myplugin.prefooter means that the plugin is type prefooter, and will appear just before the footer on the page. You can, of course simlink plugin.sh to both plugin.prefooter and plugin.postfooter if you want so that it appears twice.
- Ultra simple usage: Just type a post with your favorite editor and the script does the rest. No templating.
- No installation required. Download `bb.sh` and start blogging.
- Zero dependencies. It runs just on base utils (`date`, `basename`, `grep`, `sed`, `head`, etc)
- GNU/Linux, BSD and OSX compatible out of the box, no need for GNU `coreutils` on a Mac.
  It does some magic to autodetect which command switches it needs to run depending on your system.
- All content is static. You only need shell access to a machine with a public web folder.
  *Tip: advanced users could mount a remote public folder via `ftpfs` and run this script locally*
- Allows drafts, includes a simple but clean stylesheet, generates the RSS file automatically.
- Support for tags/categories
- Support for Markdown, Disqus comments, Twitter, Feedburner, Google Analytics.
- The project is still maintained as of 2016. Bugs are fixed, and new features are considered (see "Contributing")
- Optional powerful plugin system.
  Drop your plugins into a directory called plugins, or for system wide, /usr/share/bashblog/plugins.
- Everything stored in a single ~1k lines bash script, how cool is that?! ;) 


Plugins will have access to the settings variable in the .bashtmlrc. Just remember to source the .bashtlmrc file if they are needed. This means that your plugin will be able to use things like author, etc. Plugins are also sent the current pagename where applicable. The pre and post sync plugin types do not receive the page name.


### Plugin Types


- meta: Runs in the meta section of the head tag.
- presync: Runs before the rsync command is called.
- postsync: Runs after the rsync command is called.
- preheader: Runs just before the header section of the page.
- postheader: Runs just after the fheader section of the page.
- prefooter: Runs just before the footer section of the page.
- footer: Runs in the footer section of the page.
- postfooter: Runs just after the footer section of the page.
- post: Called when an article is created successfully.
Configuration
-------------

Configuration is not required for a test drive, but if you plan on running your blog with bashblog, you will
want to change the default titles, author names, etc, to match your own.

There are two ways to configure the blog strings:

- Edit `bb.sh` and modify the variables in the `global_variables()` function
- Create a `.config` file with your configuration values -- useful if you don't want to touch the script and be able to update it regularly with git

The software will load the values in the script first, then overwrite them with the values in the `.config` file.
This means that you don't need to define all variables in the config file, only those which you need to override
from the defaults.

The format of the `.config` file is just one `variablename="value"` per line, just like in the `global_variables()`
function. **Please remember:** quote the values, do not declare a variable with the dollar sign, do not use 
spaces around the equal sign.

bashblog uses the `$EDITOR` environment value to open the text editor.


Detailed features
-----------------

- A simple but nice and readable design, with nothing but the blog posts
- **NEW on 2.0** Markdown support via a third-party library.  
  The easiest method is to download
  Gruber's [Markdown.pl](http://daringfireball.net/projects/markdown/)
- Post preview
- Save posts as drafts and resume editing later
- HTML page for each post, using its title as the URL
- Configurable number of posts on the front page
- Automatic generation of an RSS file, feedburner support
- Additional page containing an index of all posts
- Automatically generates pages for each tag
- Rebuild all files while keeping the original data
- Comments delegated to Twitter, with additional Disqus support
- An option for cookieless Twitter sharing, to comply with the 
[EU cookie law](https://github.com/cfenollosa/eu-cookie-law)
- Google Analytics code support
- Contains its own CSS so that everything is reasonably styled by default
- Headers, footers, and in general everything that a well-structured html file needs
- Support to add extra content on top of every page (e.g. banners, images, etc)
- xhtml validation, CSS validation, RSS validation by the w3c
- Automatic backup of the site every time you post (stored as `.backup.tar.gz`)

Read the Changelog section for more updates or [check out the news on my blog](http://cfenollosa.com/blog/tag_bashblog.html)


Contributing
------------

Bashblog started at 500 SLOC and it now has hit the 1000 SLOC barrier. 
If we want to keep the code minimal and understandable, we need to make the difficult effort to restrain ourselves 
from adding too many features.

All bugfixes are welcome, but brand new features need to be strongly justified to get into the main tree. 
Every new request will be honestly and civilly discussed on the comments. 
As a guideline, pull requests should:

- Fix a use case for some people (e.g. internationalization)
- Add a use case which is arguably very common (e.g. disqus integration for comments)
- Be very small when possible (a couple lines of code)
- Don't require a significant rewrite of the code (Don't break `create_html_file()` or `write_entry()`, etc)
- It must work on Linux, BSD and Mac. Beware of using GNU coreutils with non-POSIX flags (i.e. `date` or `grep`)
- Follow the UNIX philosophy: do one thing and do it well, rely on third party software for external features, etc
- **Always** keep backwards compatibility when using the default configuration


Changelog
---------

- 2.9      Added `body_begin_file_index`
- 2.8      Bugfixes<br/>
           Slavic language support thanks to Tomasz Jadowski<br/>
           Removed the now defunct Twitter JSON API share count<br/>
           Support for static, not managed by bashblog html files<br/>
- 2.7      Store post date on a comment in the html file (#96).<br/>
           On rebuild, the post date will be synchronised between comment date and file date, with precedence for comment date.
- 2.6      Support for multiple authors, use a different `.config` for each one
- 2.5      Massive code cleanup by Martijn Dekker<br/>
           'tags' command<br/>
           The word 'posts' in the tag list (both website and command) now has a singular form, check out `template_tags_posts_singular`
- 2.4      Added Twitter summaries metadata for posts (#36)
- 2.3.3    Removed big comment header.<br/>
           Added option to display tags for cut articles on index pages (#61)<br/>
           Cleaned up "all posts" page (#57)
- 2.3.2    Option to use topsy instead of twitter for references
- 2.3.1    Cookieless Twitter option
- 2.3      Intelligent tag rebuilding and Markdown by default
- 2.2      Flexible post title -> filename conversion
- 2.1      Support for tags/categories.<br/>
           'delete' command
- 2.0.3    Support for other analytics code, via external file
- 2.0.2    Fixed bug when $body_begin_file was empty.<br/>
           Added extra line in the footer linking to the github project
- 2.0.1    Allow personalized header/footer files
- 2.0      Added Markdown support.<br/>
           Fully support BSD date
- 1.6.4    Fixed bug in localized dates
- 1.6.3    Now supporting BSD date
- 1.6.2    Simplified some functions and variables to avoid duplicated information
- 1.6.1    'date' fix when hours are 1 digit.
- 1.6.0    Disqus comments. External configuration file. Check of 'date' command version.
- 1.5.1    Misc bugfixes and parameter checks
- 1.5      Đurađ Radojičić (djura-san) refactored some code and added flexibility and i18n
- 1.4.2    Now issues are handled at Github
- 1.4.1    Some code refactoring
- 1.4      Using twitter for comments, improved 'rebuild' command
- 1.3      'edit' command
- 1.2.2    Feedburner support
- 1.2.1    Fixed the timestamps bug
- 1.2      'list' command
- 1.1      Draft and preview support
- 1.0      Read http://is.gd/Bkdoru


License
-------

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

D bashtml-plugins => bashtml-plugins +0 -1
@@ 1,1 0,0 @@
Subproject commit 276959a24dad94c7790f78a65fe98b0d8c031a64

M bashtml.sh => bashtml.sh +1192 -596
@@ 1,640 1,1236 @@
#!/bin/bash

# Global variables section. Anything use through the whole script will be initialized here.
command=(
    h # help
    n # New post
    p # New post
    r # Rebuild site
    s # sync to server using rsync
)
htmlFile="$(mktemp -t html.XXXXXXXXXXXX)"
ifs="$IFS"
mdFile="$(mktemp -t markdown.XXXXXXXXXXXX)"
scriptName="BasHTML"
# We are moving toward version 1.0
scriptVersion="0.90"
  
cleanup() {
    # This runs any time the script closes.
    # Called from the trap statement in the main body.
    local i
    for i in "$mdFile" "$htmlFile" ; do
        [[ -f "$i" ]] && rm -f "$i"
    done
     Return  IFS to its propper state
    # I dont' actually think this is necessary but better safe than sorry
    IFS="$ifs"
}
  
configuration() {
    # Loads or creates configuration file, .bashtmlrc.
    if [[ -f ".bashtmlrc" ]]; then
        source ".bashtmlrc";
        return;
#!/usr/bin/env bash

# Bashtml, by Storm Dragon.
# This is a fork of Bashblog, the original headr is below.

# BashBlog, a simple blog system written in a single bash script
# (C) Carlos Fenollosa <carlos.fenollosa@gmail.com>, 2011-2016 and contributors
# https://github.com/carlesfe/bashblog/contributors
# Check out README.md for more details

# Global variables
# It is recommended to perform a 'rebuild' after changing any of this in the code

# Config file. Any settings "key=value" written there will override the
# global_variables defaults. Useful to avoid editing bb.sh and having to deal
# with merges in VCS
global_config=".config"

# This function will load all the variables defined here. They might be overridden
# by the 'global_config' file contents
global_variables() {
    global_software_name="BashBlog"
    global_software_version="2.9"

    # Blog title
    global_title="My fancy blog"
    # The typical subtitle for each blog
    global_description="A blog about turtles and carrots"
    # The public base URL for this blog
    global_url="http://example.com/blog"

    # Your name
    global_author="John Smith"
    # You can use twitter or facebook or anything for global_author_url
    global_author_url="http://twitter.com/example" 
    # Your email
    global_email="john@smith.com"

    # CC by-nc-nd is a good starting point, you can change this to "&copy;" for Copyright
    global_license="CC by-nc-nd"

    # If you have a Google Analytics ID (UA-XXXXX) and wish to use the standard
    # embedding code, put it on global_analytics
    # If you have custom analytics code (i.e. non-google) or want to use the Universal
    # code, leave global_analytics empty and specify a global_analytics_file
    global_analytics=""
    global_analytics_file=""

    # Leave this empty (i.e. "") if you don't want to use feedburner, 
    # or change it to your own URL
    global_feedburner=""

    # Change this to your username if you want to use twitter for comments
    global_twitter_username=""
    # Set this to false for a Twitter button with share count. The cookieless version
    # is just a link.
    global_twitter_cookieless="true"
    # Default search page, where tweets more than a week old are hidden
    global_twitter_search="twitter"

    # Change this to your disqus username to use disqus for comments
    global_disqus_username=""


    # Blog generated files
    # index page of blog (it is usually good to use "index.html" here)
    index_file="index.html"
    number_of_index_articles="8"
    # global archive
    archive_index="all_posts.html"
    tags_index="all_tags.html"

    # Non blogpost files. Bashblog will ignore these. Useful for static pages and custom content
    # Add them as a bash array, e.g. non_blogpost_files=("news.html" "test.html")
    non_blogpost_files=()

    # feed file (rss in this case)
    blog_feed="feed.rss"
    number_of_feed_articles="10"
    # "cut" blog entry when putting it to index page. Leave blank for full articles in front page
    # i.e. include only up to first '<hr>', or '----' in markdown
    cut_do="cut"
    # When cutting, cut also tags? If "no", tags will appear in index page for cut articles
    cut_tags="yes"
    # Regexp matching the HTML line where to do the cut
    # note that slash is regexp separator so you need to prepend it with backslash
    cut_line='<hr ?\/?>'
    # save markdown file when posting with "bb post -m". Leave blank to discard it.
    save_markdown="yes"
    # prefix for tags/categories files
    # please make sure that no other html file starts with this prefix
    prefix_tags="tag_"
    # personalized header and footer (only if you know what you're doing)
    # DO NOT name them .header.html, .footer.html or they will be overwritten
    # leave blank to generate them, recommended
    header_file=""
    footer_file=""
    # extra content to add just after we open the <body> tag
    # and before the actual blog content
    body_begin_file=""
    # extra content to add just before we close </body>
    body_end_file=""
    # extra content to ONLY on the index page AFTER `body_begin_file` contents
    # and before the actual content
    body_begin_file_index=""
    # CSS files to include on every page, f.ex. css_include=('main.css' 'blog.css')
    # leave empty to use generated
    css_include=()
    # HTML files to exclude from index, f.ex. post_exclude=('imprint.html 'aboutme.html')
    html_exclude=()

    # Localization and i18n
    # "Comments?" (used in twitter link after every post)
    template_comments="Comments?"
    # "Read more..." (link under cut article on index page)
    template_read_more="Read more..."
    # "View more posts" (used on bottom of index page as link to archive)
    template_archive="View more posts"
    # "All posts" (title of archive page)
    template_archive_title="All posts"
    # "All tags"
    template_tags_title="All tags"
    # "posts" (on "All tags" page, text at the end of each tag line, like "2. Music - 15 posts")
    template_tags_posts="posts"
    template_tags_posts_2_4="posts"  # Some slavic languages use a different plural form for 2-4 items
    template_tags_posts_singular="post"
    # "Posts tagged" (text on a title of a page with index of one tag, like "My Blog - Posts tagged "Music"")
    template_tag_title="Posts tagged"
    # "Tags:" (beginning of line in HTML file with list of all tags for this article)
    template_tags_line_header="Tags:"
    # "Back to the index page" (used on archive page, it is link to blog index)
    template_archive_index_page="Back to the index page"
    # "Subscribe" (used on bottom of index page, it is link to RSS feed)
    template_subscribe="Subscribe"
    # "Subscribe to this page..." (used as text for browser feed button that is embedded to html)
    template_subscribe_browser_button="Subscribe to this page..."
    # "Tweet" (used as twitter text button for posting to twitter)
    template_twitter_button="Tweet"
    template_twitter_comment="&lt;Type your comment here but please leave the URL so that other people can follow the comments&gt;"
    
    # The locale to use for the dates displayed on screen
    date_format="%B %d, %Y"
    date_locale="C"
    date_inpost="bashblog_timestamp"
    # Don't change these dates
    date_format_full="%a, %d %b %Y %H:%M:%S %z"
    date_format_timestamp="%Y%m%d%H%M.%S"
    date_allposts_header="%B %Y"

    # Perform the post title -> filename conversion
    # Experts only. You may need to tune the locales too
    # Leave empty for no conversion, which is not recommended
    # This default filter respects backwards compatibility
    convert_filename="iconv -f utf-8 -t ascii//translit | sed 's/^-*//' | tr [:upper:] [:lower:] | tr ' ' '-' | tr -dc '[:alnum:]-'"

    # URL where you can view the post while it's being edited
    # same as global_url by default
    # You can change it to path on your computer, if you write posts locally
    # before copying them to the server
    preview_url=""

    # Markdown location. Trying to autodetect by default.
    # The invocation must support the signature 'markdown_bin in.md > out.html'
    [[ -f Markdown.pl ]] && markdown_bin=./Markdown.pl || markdown_bin=$(which Markdown.pl 2>/dev/null || which markdown 2>/dev/null)
}

# Check for the validity of some variables
# DO NOT EDIT THIS FUNCTION unless you know what you're doing
global_variables_check() {
    [[ $header_file == .header.html ]] &&
        echo "Please check your configuration. '.header.html' is not a valid value for the setting 'header_file'" &&
        exit
    [[ $footer_file == .footer.html ]] &&
        echo "Please check your configuration. '.footer.html' is not a valid value for the setting 'footer_file'" &&
        exit
}


# Test if the markdown script is working correctly
test_markdown() {
    [[ -n $markdown_bin ]] &&
        (
        [[ $("$markdown_bin" <<< $'line 1\n\nline 2') == $'<p>line 1</p>\n\n<p>line 2</p>' ]] ||
        [[ $("$markdown_bin" <<< $'line 1\n\nline 2') == $'<p>line 1</p>\n<p>line 2</p>' ]]
        )
}


# Parse a Markdown file into HTML and return the generated file
markdown() {
    out=${1%.md}.html
    while [[ -f $out ]]; do out=${out%.html}.$RANDOM.html; done
    $markdown_bin "$1" > "$out"
    echo "$out"
}


# Prints the required google analytics code
google_analytics() {
    [[ -z $global_analytics && -z $global_analytics_file ]]  && return

    if [[ -z $global_analytics_file ]]; then
        echo "<script type=\"text/javascript\">

        var _gaq = _gaq || [];
        _gaq.push(['_setAccount', '${global_analytics}']);
        _gaq.push(['_trackPageview']);

        (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
        })();

        </script>"
    else
        cat "$global_analytics_file"
    fi
    # No configuration file was detected, so write it
    # The next part of this function is left-aligned easier with cat EOF.
cat << EOF > .bashtmlrc
declare -Ag settings=(
[author]="Anonymous" # Your Name.
[authorURL]="" # Anything you want, GNU Social, Mastodon, Diaspora, etc.
[email]="" # Protected by javascript if given.
[css]="default.css" # place stylesheets in bashtml-css/
[dateFormat]="%A, %B %d, %Y" # man date for format strings
[editor]="${EDITOR:-nano}" # for writing posts
[maxIndex]="10" # Number of articles shown on index page
[pageExtension]="html" # Configurable in case you want to add php code or whatever.
[blogName]="BasHTML" # The name of your blog.
[blogDescription]="A blog generated using $(bash --version | head -1 | cut -d '-' -f1)." # Short description.
[blogURL]="" # The full URL to your site.
[gnuSocialURL]="https://2mb.social" # The GNU Social url used for tags in posts
[license]="CC BY-NC-ND"
[licenseURL]="https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode"
[rsyncAddress]="" # Server:path where files should be uploaded.
[rsyncDelete]="no" # Should files that do not exist on the local machine be deleted from the server during sync?
[rsyncExcludes]=".bashtmlrc *.md bashtml-plugins/" # Things rsync should not copy to the server.
[rsyncPasswordFile]="" # Full path to rsync password file, if not specified, you will be prompted.
[rsyncUser]="" # User rsync should sync as, e.g. http
)
EOF
    # Exit so configuration can be customized.
    echo ".bashtmlrc configuration has been created. Please edit it to your liking and run ${0##*/} again." | fold -s
    exit 0
}

init() {
    # setup for  a new site
    # This is ran each time bashtml starts, to check dependancies and directory structures.
    # Check installed dependancies
    local i
    local dependencies=(
        "markdown" # tested with discount, other markdown providers may require changing the code.
    )
    for i in "${dependencies[@]}" ; do
        command -v "$i" &> /dev/null || {
            echo "Please install $i before using $scriptName.";
            exit 1;
}

# Prints the required code for disqus comments
disqus_body() {
    [[ -z $global_disqus_username ]] && return

    echo '<div id="disqus_thread"></div>
            <script type="text/javascript">
            /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
               var disqus_shortname = '"'$global_disqus_username'"'; // required: replace example with your forum shortname

            /* * * DONT EDIT BELOW THIS LINE * * */
            (function() {
            var dsq = document.createElement("script"); dsq.type = "text/javascript"; dsq.async = true;
            dsq.src = "//" + disqus_shortname + ".disqus.com/embed.js";
            (document.getElementsByTagName("head")[0] || document.getElementsByTagName("body")[0]).appendChild(dsq);
            })();
            </script>
            <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
            <a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>'
}

# Prints the required code for disqus in the footer
disqus_footer() {
    [[ -z $global_disqus_username ]] && return
    echo '<script type="text/javascript">
        /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
        var disqus_shortname = '"'$global_disqus_username'"'; // required: replace example with your forum shortname

        /* * * DONT EDIT BELOW THIS LINE * * */
        (function () {
        var s = document.createElement("script"); s.async = true;
        s.type = "text/javascript";
        s.src = "//" + disqus_shortname + ".disqus.com/count.js";
        (document.getElementsByTagName("HEAD")[0] || document.getElementsByTagName("BODY")[0]).appendChild(s);
    }());
    </script>'
}

# Reads HTML file from stdin, prints its content to stdout
# $1    where to start ("text" or "entry")
# $2    where to stop ("text" or "entry")
# $3    "cut" to remove text from <hr /> to <!-- text end -->
#       note that this does not remove <hr /> line itself,
#       so you can see if text was cut or not
get_html_file_content() {
    awk "/<!-- $1 begin -->/, /<!-- $2 end -->/{
        if (!/<!-- $1 begin -->/ && !/<!-- $2 end -->/) print
        if (\"$3\" == \"cut\" && /$cut_line/){
            if (\"$2\" == \"text\") exit # no need to read further
            while (getline > 0 && !/<!-- text end -->/) {
                if (\"$cut_tags\" == \"no\" && /^<p>$template_tags_line_header/ ) print 
            }
        }
    done
    # Base64 encode author's email address if set
    # If already encoded to base64, the last character will be =
    if [[ -n "${settings[email]}" ]]; then
        if [[ "${settings[email]:$((${#settings[email]} - 1))}" != '=' ]]; then
            # Update the variable both in the current script and the settings file
            sed -i "s/\[email\]=\"\(.*\)\"\(.*\)/[email]=\"$(echo "${settings[email]}" | base64)\"\2/"  ".bashtmlrc"
            settings[email]="$(echo "${settings[email]}" | base64)"
            # Remove the old script, if any.
            rm bashtml-scripts/email.js &> /dev/null
            initialize_bashtml-scripts
    }"
}

# Edit an existing, published .html file while keeping its original timestamp
# Please note that this function does not automatically republish anything, as
# it is usually called from 'main'.
#
# Note that it edits HTML file, even if you wrote the post as markdown originally
# Note that if you edit title then filename might also change
#
# $1 	the file to edit
# $2	(optional) edit mode:
#	"keep" to keep old filename
#	"full" to edit full HTML, and not only text part (keeps old filename)
#	leave empty for default behavior (edit only text part and change name)
edit() {
    [[ ! -f "${1%%.*}.html" ]] && echo "Can't edit post "${1%%.*}.html", did you mean to use \"bb.sh post <draft_file>\"?" && exit -1
    # Original post timestamp
    edit_timestamp=$(LC_ALL=C date -r "${1%%.*}.html" +"$date_format_full" )
    touch_timestamp=$(LC_ALL=C date -r "${1%%.*}.html" +"$date_format_timestamp")
    tags_before=$(tags_in_post "${1%%.*}.html")
    if [[ $2 == full ]]; then
        $EDITOR "$1"
        filename=$1
    else
        if [[ ${1##*.} == md ]]; then
            test_markdown
            if (($? != 0)); then
                echo "Markdown is not working, please edit HTML file directly."
                exit
            fi
            # editing markdown file
            $EDITOR "$1"
            TMPFILE=$(markdown "$1")
            filename=${1%%.*}.html
        else
            # Create the content file
            TMPFILE=$(basename "$1").$RANDOM.html
            # Title
            get_post_title "$1" > "$TMPFILE"
            # Post text with plaintext tags
            get_html_file_content 'text' 'text' <"$1" | sed "/^<p>$template_tags_line_header/s|<a href='$prefix_tags\([^']*\).html'>\\1</a>|\\1|g" >> "$TMPFILE"
            $EDITOR "$TMPFILE"
            filename=$1
        fi
        rm "$filename"
        if [[ $2 == keep ]]; then
            parse_file "$TMPFILE" "$edit_timestamp" "$filename"
        else
            parse_file "$TMPFILE" "$edit_timestamp" # this command sets $filename as the html processed file
            [[ ${1##*.} == md ]] && mv "$1" "${filename%%.*}.md" 2>/dev/null
        fi
        rm "$TMPFILE"
    fi
    # create directories
    local directories=(
        bashtml-css
        bashtml-plugins
        bashtml-scripts
    )
    for i in "${directories[@]}" ; do
        if ! [[ -d "$i" ]]; then
            mkdir "$i"
            declare -f "initialize_$i" &> /dev/null && "initialize_$i"
    touch -t "$touch_timestamp" "$filename"
    touch -t "$touch_timestamp" "$1"
    chmod 644 "$filename"
    echo "Posted $filename"
    call_plugins posted_html
    tags_after=$(tags_in_post "$filename")
    relevant_tags=$(echo "$tags_before $tags_after" | tr ',' ' ' | tr ' ' '\n' | sort -u | tr '\n' ' ')
    if [[ ! -z $relevant_tags ]]; then
        relevant_posts="$(posts_with_tags $relevant_tags) $filename"
        rebuild_tags "$relevant_posts" "$relevant_tags"
    fi
}

# Create a Twitter summary (twitter "card") for the post
#
# $1 the post file
# $2 the title
twitter_card() {
    [[ -z $global_twitter_username ]] && return
    
    echo "<meta name='twitter:card' content='summary' />"
    echo "<meta name='twitter:site' content='@$global_twitter_username' />"
    echo "<meta name='twitter:title' content='$2' />" # Twitter truncates at 70 char
    description=$(grep -v "^<p>$template_tags_line_header" "$1" | sed -e 's/<[^>]*>//g' | tr '\n' ' ' | sed "s/\"/'/g" | head -c 250) 
    echo "<meta name='twitter:description' content=\"$description\" />"
    image=$(sed -n '2,$ d; s/.*<img.*src="\([^"]*\)".*/\1/p' "$1") # First image is fine
    [[ -z $image ]] && return
    [[ $image =~ ^https?:// ]] || image=$global_url/$image # Check that URL is absolute
    echo "<meta name='twitter:image' content='$image' />"
}

# Adds the code needed by the twitter button
#
# $1 the post URL
twitter() {
    [[ -z $global_twitter_username ]] && return

    if [[ -z $global_disqus_username ]]; then
        if [[ $global_twitter_cookieless == true ]]; then 
            id=$RANDOM

            search_engine="https://twitter.com/search?q="

            echo "<p id='twitter'><a href='http://twitter.com/intent/tweet?url=$1&text=$template_twitter_comment&via=$global_twitter_username'>$template_comments $template_twitter_button</a> "
            echo "<a href='$search_engine""$1'><span id='count-$id'></span></a>&nbsp;</p>"
            return;
        else 
            echo "<p id='twitter'>$template_comments&nbsp;"; 
        fi
    done
    # Write robots.txt file
    robots_txt
    else
        echo "<p id='twitter'><a href=\"$1#disqus_thread\">$template_comments</a> &nbsp;"
    fi  

    echo "<a href=\"https://twitter.com/share\" class=\"twitter-share-button\" data-text=\"$template_twitter_comment\" data-url=\"$1\""
    echo " data-via=\"$global_twitter_username\""
    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>"
    echo "</p>"
}

robots_txt() {
    # If robots.txt doesn't exist, create it.
    if ! [[ -f robots.txt ]]; then
        touch robots.txt
    fi
    # Add all spiders if it's not found on first line
    if [[ "$(head -1 robots.txt)" != 'User-agent: *' ]]; then
        sed -i -e '/U#ser-agent:/d' -e '1s/^/User-agent: *\n/' robots.txt
    fi
  # Now add non-allowed directories and files.
    local disallowed=(
        /bashtml-css/
        /bashtml-plugins/
        /bashtml-scripts/
        /.bashtmlrc
        '/*.md'
    )
    for i in "${disallowed[@]}" ; do
        grep -qx "Disallow: $i" robots.txt || echo "Disallow: $i" >> robots.txt
# Check if the file is a 'boilerplate' (i.e. not a post)
# The return values are designed to be used like this inside a loop:
# is_boilerplate_file <file> && continue
#
# $1 the file
#
# Return 0 (bash return value 'true') if the input file is an index, feed, etc
# or 1 (bash return value 'false') if it is a blogpost
is_boilerplate_file() {
    name=${1#./}
    # First check against user-defined non-blogpost pages
    for item in "${non_blogpost_files[@]}"; do
        [[ "$name" == "$item" ]] && return 0
    done

    case $name in
    ( "$index_file" | "$archive_index" | "$tags_index" | "$footer_file" | "$header_file" | "$global_analytics_file" | "$prefix_tags"* )
        return 0 ;;
    ( * ) # Check for excluded
        for excl in "${html_exclude[@]}"; do
            [[ $name == "$excl" ]] && return 0
        done
        return 1 ;;
    esac
}

# Adds all the bells and whistles to format the html page
# Every blog post is marked with a <!-- entry begin --> and <!-- entry end -->
# which is parsed afterwards in the other functions. There is also a marker
# <!-- text begin --> to determine just the beginning of the text body of the post
#
# $1     a file with the body of the content
# $2     the output file
# $3     "yes" if we want to generate the index.html,
#        "no" to insert new blog posts
# $4     title for the html header
# $5     original blog timestamp
# $6     post author
create_html_page() {
    content=$1
    filename=$2
    index=$3
    title=$4
    timestamp=$5
    author=$6

    # Create the actual blog post
    # html, head
    {
        cat ".header.html"
        echo "<title>$title</title>"
        google_analytics
        twitter_card "$content" "$title"
        echo "</head><body>"
        # stuff to add before the actual body content
        [[ -n $body_begin_file ]] && cat "$body_begin_file"
        [[ $filename = $index_file* ]] && [[ -n $body_begin_file_index ]] && cat "$body_begin_file_index"
        # body divs
        echo '<div id="divbodyholder">'
        echo '<div class="headerholder"><div class="header">'
        # blog title
        echo '<div id="title">'
        cat .title.html
        echo '</div></div></div>' # title, header, headerholder
        echo '<div id="divbody"><div class="content">'

        file_url=${filename#./}
        file_url=${file_url%.rebuilt} # Get the correct URL when rebuilding
        # one blog entry
        if [[ $index == no ]]; then
            echo '<!-- entry begin -->' # marks the beginning of the whole post
            echo "<h3><a class=\"ablack\" href=\"$file_url\">"
            # remove possible <p>'s on the title because of markdown conversion
            title=${title//<p>/}
            title=${title//<\/p>/}
            echo "$title"
            echo '</a></h3>'
            if [[ -z $timestamp ]]; then
                echo "<!-- $date_inpost: #$(LC_ALL=$date_locale date +"$date_format_timestamp")# -->"
            else
                echo "<!-- $date_inpost: #$(LC_ALL=$date_locale date +"$date_format_timestamp" --date="$timestamp")# -->"
            fi
            if [[ -z $timestamp ]]; then
                echo -n "<div class=\"subtitle\">$(LC_ALL=$date_locale date +"$date_format")"
            else
                echo -n "<div class=\"subtitle\">$(LC_ALL=$date_locale date +"$date_format" --date="$timestamp")"
            fi
            [[ -n $author ]] && echo -e " &mdash; \n$author"
            echo "</div>"
            echo '<!-- text begin -->' # This marks the text body, after the title, date...
        fi
        cat "$content" # Actual content
        if [[ $index == no ]]; then
            echo -e '\n<!-- text end -->'

            twitter "$global_url/$file_url"

            echo '<!-- entry end -->' # absolute end of the post
        fi

        echo '</div>' # content

        # Add disqus commments except for index and all_posts pages
        [[ $index == no ]] && disqus_body

        # page footer
        cat .footer.html
        # close divs
        echo '</div></div>' # divbody and divbodyholder 
        disqus_footer
        [[ -n $body_end_file ]] && cat "$body_end_file"
        echo '</body></html>'
    } > "$filename"
}

initialize_bashtml-scripts() {
    # Create email protection script
    if [[ -n "${settings[email]}" ]]; then
    # Heredocument left aligned
cat << EOF > "bashtml-scripts/email.js"
//	  <!--
decodeBase64 = function(s) {
    var e={},i,b=0,c,x,l=0,a,r='',w=String.fromCharCode,L=s.length;
    var A="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    for(i=0;i<64;i++){e[A.charAt(i)]=i;}
    for(x=0;x<L;x++){
        c=e[s.charAt(x)];b=(b<<6)+c;l+=6;
        while(l>=8){((a=(b>>>(l-=8))&0xff)||(x<(L-2)))&&(r+=w(a));}
    }
    return r;
};
document.write('<a href="mailto://' + decodeBase64('${settings[email]}') + '">contact ${settings[author]} at ' + decodeBase64('${settings[email]}') + '</a>');
	  //-->
# Parse the plain text file into an html file
#
# $1    source file name
# $2    (optional) timestamp for the file
# $3    (optional) destination file name
# note that although timestamp is optional, something must be provided at its
# place if destination file name is provided, i.e:
# parse_file source.txt "" destination.html
parse_file() {
    # Read for the title and check that the filename is ok
    title=""
    while IFS='' read -r line; do
        if [[ -z $title ]]; then
            # remove extra <p> and </p> added by markdown
            title=$(echo "$line" | sed 's/<\/*p>//g')
            if [[ -n $3 ]]; then
                filename=$3
            else
                filename=$title
                [[ -n $convert_filename ]] &&
                    filename=$(echo "$title" | eval "$convert_filename")
                [[ -n $filename ]] || 
                    filename=$RANDOM # don't allow empty filenames

                filename=$filename.html

                # Check for duplicate file names
                while [[ -f $filename ]]; do
                    filename=${filename%.html}$RANDOM.html
                done
            fi
            content=$filename.tmp
        # Parse possible tags
        elif [[ $line == "<p>$template_tags_line_header"* ]]; then
            tags=$(echo "$line" | cut -d ":" -f 2- | sed -e 's/<\/p>//g' -e 's/^ *//' -e 's/ *$//' -e 's/, /,/g')
            IFS=, read -r -a array <<< "$tags"

            echo -n "<p>$template_tags_line_header " >> "$content"
            for item in "${array[@]}"; do
                echo -n "<a href='$prefix_tags$item.html'>$item</a>, "
            done | sed 's/, $/<\/p>/g' >> "$content"
        else
            echo "$line" >> "$content"
        fi
    done < "$1"

    # Create the actual html page
    create_html_page "$content" "$filename" no "$title" "$2" "$global_author"
    rm "$content"
}

# Manages the creation of the text file and the parsing to html file
# also the drafts
write_entry() {
    test_markdown && fmt=md || fmt=html
    f=$2
    [[ $2 == -html ]] && fmt=html && f=$3

    if [[ -n $f ]]; then
        TMPFILE=$f
        if [[ ! -f $TMPFILE ]]; then
            echo "The file doesn't exist"
            delete_includes
            exit
        fi
        # guess format from TMPFILE
        extension=${TMPFILE##*.}
        [[ $extension == md || $extension == html ]] && fmt=$extension
        # but let user override it (`bb.sh post -html file.md`)
        [[ $2 == -html ]] && fmt=html
        # Test if Markdown is working before re-posting a .md file
        if [[ $extension == md ]]; then
            test_markdown
            if (($? != 0)); then
                echo "Markdown is not working, please edit HTML file directly."
                exit
            fi
        fi
    else
        TMPFILE=.entry-$RANDOM.$fmt
        echo -e "Title on this line\n" >> "$TMPFILE"

        [[ $fmt == html ]] && cat << EOF >> "$TMPFILE"
<p>The rest of the text file is an <b>html</b> blog post. The process will continue as soon
as you exit your editor.</p>

<p>$template_tags_line_header keep-this-tag-format, tags-are-optional, example</p>
EOF
        [[ $fmt == md ]] && cat << EOF >> "$TMPFILE"
The rest of the text file is a **Markdown** blog post. The process will continue
as soon as you exit your editor.

$template_tags_line_header keep-this-tag-format, tags-are-optional, beware-with-underscores-in-markdown, example
EOF
    # Heredocument end
    fi
    chmod 600 "$TMPFILE"

    post_status="E"
    filename=""
    while [[ $post_status != "p" && $post_status != "P" ]]; do
        [[ -n $filename ]] && rm "$filename" # Delete the generated html file, if any
        call_plugins pre_edit "$TMPFILE"
        $EDITOR "$TMPFILE"
        call_plugins post_edit "$TMPFILE"
        if [[ $fmt == md ]]; then
            html_from_md=$(markdown "$TMPFILE")
            parse_file "$html_from_md"
            rm "$html_from_md"
        else
            parse_file "$TMPFILE" # this command sets $filename as the html processed file
        fi

        chmod 644 "$filename"
        [[ -n $preview_url ]] || preview_url=$global_url
        echo "To preview the entry, open $preview_url/$filename in your browser"

        echo -n "[P]ost this entry, [E]dit again, [D]raft for later? (p/E/d) "
        read -r post_status
        if [[ $post_status == d || $post_status == D ]]; then
            mkdir -p "drafts/"
            chmod 700 "drafts/"

            title=$(head -n 1 $TMPFILE)
            [[ -n $convert_filename ]] && title=$(echo "$title" | eval "$convert_filename")
            [[ -n $title ]] || title=$RANDOM

            draft=drafts/$title.$fmt
            mv "$TMPFILE" "$draft"
            chmod 600 "$draft"
            rm "$filename"
            delete_includes
            echo "Saved your draft as '$draft'"
            exit
        fi
    done

    if [[ $fmt == md && -n $save_markdown ]]; then
        mv "$TMPFILE" "${filename%%.*}.md"
    else
        rm "$TMPFILE"
    fi
    chmod 644 "$filename"
    echo "Posted $filename"
    call_plugins posted_md
    relevant_tags=$(tags_in_post $filename)
    if [[ -n $relevant_tags ]]; then
        relevant_posts="$(posts_with_tags $relevant_tags) $filename"
        rebuild_tags "$relevant_posts" "$relevant_tags"
    fi
}

initialize_bashtml-css() {
    # write  default html file.
    # http://matthewjamestaylor.com/blog/perfect-full-page.htm
# Heredocument left aligned
cat << EOF > bashtml-css/default.css
	/* <!-- */
	/* General styles */
/* http://matthewjamestaylor.com/blog/perfect-full-page.htm */
	body {
		margin:0;
		padding:0;
		border:0;			/* This removes the border around the viewport in old versions of IE */
		width:100%;
		background:#fff;
		min-width:600px;		/* Minimum width of layout - remove line if not required */
						/* The min-width property does not work in old versions of Internet Explorer */
		font-size:90%;
	}
	a {
		color:#369;
	}
	a:hover {
		color:#fff;
		background:#369;
		text-decoration:none;
	}
	h1, h2, h3 {
		margin:.8em 0 .2em 0;
		padding:0;
	}
	p {
		margin:.4em 0 .8em 0;
		padding:0;
	}
	img {
		margin:10px 0 5px;
	}
	/* Header styles */
	#header {
		clear:both;
		float:left;
		width:100%;
	}
	#header {
		border-bottom:1px solid #000;
	}
	#header p,
	#header h1,
	#header h2 {
		padding:.4em 15px 0 15px;
		margin:0;
	}
	#header ul {
		clear:left;
		float:left;
		width:100%;
		list-style:none;
		margin:10px 0 0 0;
		padding:0;
	}
	#header ul li {
		display:inline;
		list-style:none;
		margin:0;
		padding:0;
	}
	#header ul li a {
		display:block;
		float:left;
		margin:0 0 0 1px;
		padding:3px 10px;
		text-align:center;
		background:#eee;
		color:#000;
		text-decoration:none;
		position:relative;
		left:15px;
		line-height:1.3em;
	}
	#header ul li a:hover {
		background:#369;
		color:#fff;
	}
	#header ul li a.active,
	#header ul li a.active:hover {
		color:#fff;
		background:#000;
		font-weight:bold;
	}
	#header ul li a span {
		display:block;
	}
	/* 'widths' sub menu */
	#layoutdims {
		clear:both;
		background:#eee;
		border-top:4px solid #000;
		margin:0;
		padding:6px 15px !important;
		text-align:right;
	}
	/* column container */
	.colmask {
		position:relative;	/* This fixes the IE7 overflow hidden bug */
		clear:both;
		float:left;
		width:100%;			/* width of whole page */
		overflow:hidden;		/* This chops off any overhanging divs */
	}
	/* common column settings */
	.colright,
	.colmid,
	.colleft {
		float:left;
		width:100%;
		position:relative;
	}
	.col1,
	.col2,
	.col3 {
		float:left;
		position:relative;
		padding:0 0 1em 0;
		overflow:hidden;
	}
	/* Full page settings */
	.fullpage {
		background:#fff;		/* page background colour */
	}
	.fullpage .col1 {
		width:96%;			/* page width minus left and right padding */
		left:2%;			/* page left padding */
	}
	/* Footer styles */
	#footer {
		clear:both;
		float:left;
		width:100%;
		border-top:1px solid #000;
	}
	#footer p {
		padding:10px;
		margin:0;
	}
	/* --> */
EOF
    # Heredocument end
# Create an index page with all the posts
all_posts() {
    echo -n "Creating an index page with all the posts "
    contentfile=$archive_index.$RANDOM
    while [[ -f $contentfile ]]; do
        contentfile=$archive_index.$RANDOM
    done

    {
        echo "<h3>$template_archive_title</h3>"
        prev_month=""
        while IFS='' read -r i; do
            is_boilerplate_file "$i" && continue
            echo -n "." 1>&3
            # Month headers
            month=$(LC_ALL=$date_locale date -r "$i" +"$date_allposts_header")
            if [[ $month != "$prev_month" ]]; then
                [[ -n $prev_month ]] && echo "</ul>"  # Don't close ul before first header
                echo "<h4 class='allposts_header'>$month</h4>"
                echo "<ul>"
                prev_month=$month
            fi
            # Title
            title=$(get_post_title "$i")
            echo -n "<li><a href=\"$i\">$title</a> &mdash;"
            # Date
            date=$(LC_ALL=$date_locale date -r "$i" +"$date_format")
            echo " $date</li>"
        done < <(ls -t ./*.html)
        echo "" 1>&3
        echo "</ul>"
        echo "<div id=\"all_posts\"><a href=\"./$index_file\">$template_archive_index_page</a></div>"
    } 3>&1 >"$contentfile"

    create_html_page "$contentfile" "$archive_index.tmp" yes "$global_title &mdash; $template_archive_title" "$global_author"
    mv "$archive_index.tmp" "$archive_index"
    chmod 644 "$archive_index"
    rm "$contentfile"
}

run_plugins() {
    # $1 is the type of plugin to run. 
    mapfile -t plugins < <(find bashtml-plugins/ -iname "*.$1" 2> /dev/null)
    # We are done with $1, so remove it 
    shift
    unset i
    for i in "${plugins[@]}" ; do
        ./"$i" "${@}"
# Create an index page with all the tags
all_tags() {
    echo -n "Creating an index page with all the tags "
    contentfile=$tags_index.$RANDOM
    while [[ -f $contentfile ]]; do
        contentfile=$tags_index.$RANDOM
    done

    {
        echo "<h3>$template_tags_title</h3>"
        echo "<ul>"
        for i in $prefix_tags*.html; do
            [[ -f "$i" ]] || break
            echo -n "." 1>&3
            nposts=$(grep -c "<\!-- text begin -->" "$i")
            tagname=${i#"$prefix_tags"}
            tagname=${tagname%.html}
            case $nposts in
                1) word=$template_tags_posts_singular;;
                2|3|4) word=$template_tags_posts_2_4;;
                *) word=$template_tags_posts;;
            esac
            echo "<li><a href=\"$i\">$tagname</a> &mdash; $nposts $word</li>"
        done
        echo "" 1>&3
        echo "</ul>"
        echo "<div id=\"all_posts\"><a href=\"./$index_file\">$template_archive_index_page</a></div>"
    } 3>&1 > "$contentfile"

    create_html_page "$contentfile" "$tags_index.tmp" yes "$global_title &mdash; $template_tags_title" "$global_author"
    mv "$tags_index.tmp" "$tags_index"
    chmod 644 "$tags_index"
    rm "$contentfile"
}

show_help() {
    echo "To get started, run ${0##*/} with no arguments."
    echo "Edit the configuration file, \".${0##*/}rc\" to your liking."
    echo "Run ${0##*/} with the -p flag to create a post."
    echo
    echo "for more in depth help, including the use of plugins, please see the README file."
# Generate the index.html with the content of the latest posts
rebuild_index() {
    echo -n "Rebuilding the index "
    newindexfile=$index_file.$RANDOM
    contentfile=$newindexfile.content
    while [[ -f $newindexfile ]]; do 
        newindexfile=$index_file.$RANDOM
        contentfile=$newindexfile.content
    done

    # Create the content file
    {
        n=0
        while IFS='' read -r i; do
            is_boilerplate_file "$i" && continue;
            if ((n >= number_of_index_articles)); then break; fi
            if [[ -n $cut_do ]]; then
                get_html_file_content 'entry' 'entry' 'cut' <"$i" | awk "/$cut_line/ { print \"<p class=\\\"readmore\\\"><a href=\\\"$i\\\">$template_read_more</a></p>\" ; next } 1"
            else
                get_html_file_content 'entry' 'entry' <"$i"
            fi
            echo -n "." 1>&3
            n=$(( n + 1 ))
        done < <(ls -t ./*.html) # sort by date, newest first

        feed=$blog_feed
        if [[ -n $global_feedburner ]]; then feed=$global_feedburner; fi
        echo "<div id=\"all_posts\"><a href=\"$archive_index\">$template_archive</a> &mdash; <a href=\"$tags_index\">$template_tags_title</a> &mdash; <a href=\"$feed\">$template_subscribe</a></div>"
    } 3>&1 >"$contentfile"

    echo ""

    create_html_page "$contentfile" "$newindexfile" yes "$global_title" "$global_author"
    rm "$contentfile"
    mv "$newindexfile" "$index_file"
    chmod 644 "$index_file"
}

sync_to_server() {
    # Minimal validation for settings.
    if [[ "${settings[rsyncAddress]}" == "" ]]; then
        echo "No address specified. Please edit your .bashtmlrc file and configure the rsync settings."
        exit 1
# Finds all tags referenced in one post.
# Accepts either filename as first argument, or post content at stdin
# Prints one line with space-separated tags to stdout
tags_in_post() {
    sed -n "/^<p>$template_tags_line_header/{s/^<p>$template_tags_line_header//;s/<[^>]*>//g;s/[ ,]\+/ /g;p;}" "$1" | tr ', ' ' '
}

# Finds all posts referenced in a number of tags.
# Arguments are tags
# Prints one line with space-separated tags to stdout
posts_with_tags() {
    (($# < 1)) && return
    set -- "${@/#/$prefix_tags}"
    set -- "${@/%/.html}"
    sed -n '/^<h3><a class="ablack" href="[^"]*">/{s/.*href="\([^"]*\)">.*/\1/;p;}' "$@" 2> /dev/null
}

# Rebuilds tag_*.html files
# if no arguments given, rebuilds all of them
# if arguments given, they should have this format:
# "FILE1 [FILE2 [...]]" "TAG1 [TAG2 [...]]"
# where FILEn are files with posts which should be used for rebuilding tags,
# and TAGn are names of tags which should be rebuilt.
# example:
# rebuild_tags "one_post.html another_article.html" "example-tag another-tag"
# mind the quotes!
rebuild_tags() {
    if (($# < 2)); then
        # will process all files and tags
        files=$(ls -t ./*.html)
        all_tags=yes
    else
        # will process only given files and tags
        files=$(printf '%s\n' $1 | sort -u)
        files=$(ls -t $files)
        tags=$2
    fi
    if [[ "${settings[rsyncUser]}" == "" ]]; then
        echo "No user name specified. Please edit your .bashtmlrc file and configure the rsync settings."
        exit 1
    echo -n "Rebuilding tag pages "
    n=0
    if [[ -n $all_tags ]]; then
        rm ./"$prefix_tags"*.html &> /dev/null
    else
        for i in $tags; do
            rm "./$prefix_tags$i.html" &> /dev/null
        done
    fi
    # Presync plugins
    run_plugins presync
    # Store arguments to rsync in a variable
    local rsyncArgs=('-hPrszz')
    if [[ "${settings[rsyncPasswordFile]}" != "" ]]; then
        rsyncArgs+=("--password-file=${settings[rsyncPasswordFile]}")
    # First we will process all files and create temporal tag files
    # with just the content of the posts
    tmpfile=tmp.$RANDOM
    while [[ -f $tmpfile ]]; do tmpfile=tmp.$RANDOM; done
    while IFS='' read -r i; do
        is_boilerplate_file "$i" && continue;
        echo -n "."
        if [[ -n $cut_do ]]; then
            get_html_file_content 'entry' 'entry' 'cut' <"$i" | awk "/$cut_line/ { print \"<p class=\\\"readmore\\\"><a href=\\\"$i\\\">$template_read_more</a></p>\" ; next } 1"
        else
            get_html_file_content 'entry' 'entry' <"$i"
        fi >"$tmpfile"
        for tag in $(tags_in_post "$i"); do
            if [[ -n $all_tags || " $tags " == *" $tag "* ]]; then
                cat "$tmpfile" >> "$prefix_tags$tag".tmp.html
            fi
        done
    done <<< "$files"
    rm "$tmpfile"
    # Now generate the tag files with headers, footers, etc
    while IFS='' read -r i; do
        tagname=${i#./"$prefix_tags"}
        tagname=${tagname%.tmp.html}
        create_html_page "$i" "$prefix_tags$tagname.html" yes "$global_title &mdash; $template_tag_title \"$tagname\"" "$global_author"
        rm "$i"
    done < <(ls -t ./"$prefix_tags"*.tmp.html 2>/dev/null)
    echo
}

# Return the post title
#
# $1 the html file
get_post_title() {
    awk '/<h3><a class="ablack" href=".+">/, /<\/a><\/h3>/{if (!/<h3><a class="ablack" href=".+">/ && !/<\/a><\/h3>/) print}' "$1"
}

# Return the post author
#
# $1 the html file
get_post_author() { 
    awk '/<div class="subtitle">.+/, /<!-- text begin -->/{if (!/<div class="subtitle">.+/ && !/<!-- text begin -->/) print}' "$1" | sed 's/<\/div>//g'
}

# Displays a list of the tags
#
# $2 if "-n", tags will be sorted by number of posts
list_tags() {
    if [[ $2 == -n ]]; then do_sort=1; else do_sort=0; fi

    ls ./$prefix_tags*.html &> /dev/null
    (($? != 0)) && echo "No posts yet. Use 'bb.sh post' to create one" && return

    lines=""
    for i in $prefix_tags*.html; do
        [[ -f "$i" ]] || break
        nposts=$(grep -c "<\!-- text begin -->" "$i")
        tagname=${i#"$prefix_tags"}
        tagname=${tagname#.html}
        ((nposts > 1)) && word=$template_tags_posts || word=$template_tags_posts_singular
        line="$tagname # $nposts # $word"
        lines+=$line\\n
    done

    if (( do_sort == 1 )); then
        echo -e "$lines" | column -t -s "#" | sort -nrk 2
    else
        echo -e "$lines" | column -t -s "#" 
    fi
    if [[ "${settings[rsyncDelete],,}" == "yes" ]]; then
        rsyncArgs+=("--delete" "--delete-excluded")
}

# Displays a list of the posts
list_posts() {
    ls ./*.html &> /dev/null
    (($? != 0)) && echo "No posts yet. Use 'bb.sh post' to create one" && return

    lines=""
    n=1
    while IFS='' read -r i; do
        is_boilerplate_file "$i" && continue
        line="$n # $(get_post_title "$i") # $(LC_ALL=$date_locale date -r "$i" +"$date_format")"
        lines+=$line\\n
        n=$(( n + 1 ))
    done < <(ls -t ./*.html)

    echo -e "$lines" | column -t -s "#"
}

# Generate the feed file
make_rss() {
    echo -n "Making RSS "

    rssfile=$blog_feed.$RANDOM
    while [[ -f $rssfile ]]; do rssfile=$blog_feed.$RANDOM; done

    {
        pubdate=$(LC_ALL=C date +"$date_format_full")
        echo '<?xml version="1.0" encoding="UTF-8" ?>' 
        echo '<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">' 
        echo "<channel><title>$global_title</title><link>$global_url/$index_file</link>"
        echo "<description>$global_description</description><language>en</language>"
        echo "<lastBuildDate>$pubdate</lastBuildDate>"
        echo "<pubDate>$pubdate</pubDate>"
        echo "<atom:link href=\"$global_url/$blog_feed\" rel=\"self\" type=\"application/rss+xml\" />"
    
        n=0
        while IFS='' read -r i; do
            is_boilerplate_file "$i" && continue
            ((n >= number_of_feed_articles)) && break # max 10 items
            echo -n "." 1>&3
            echo '<item><title>' 
            get_post_title "$i"
            echo '</title><description><![CDATA[' 
            get_html_file_content 'text' 'entry' $cut_do <"$i"
            echo "]]></description><link>$global_url/${i#./}</link>" 
            echo "<guid>$global_url/$i</guid>" 
            echo "<dc:creator>$(get_post_author "$i")</dc:creator>" 
            echo "<pubDate>$(LC_ALL=C date -r "$i" +"$date_format_full")</pubDate></item>"
    
            n=$(( n + 1 ))
        done < <(ls -t ./*.html)
    
        echo '</channel></rss>'
    } 3>&1 >"$rssfile"
    echo ""

    mv "$rssfile" "$blog_feed"
    chmod 644 "$blog_feed"
}

# generate headers, footers, etc
create_includes() {
    {
        echo "<h1 class=\"nomargin\"><a class=\"ablack\" href=\"$global_url/$index_file\">$global_title</a></h1>" 
        echo "<div id=\"description\">$global_description</div>"
    } > ".title.html"

    if [[ -f $header_file ]]; then cp "$header_file" .header.html
    else {
        echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'
        echo '<html xmlns="http://www.w3.org/1999/xhtml"><head>'
        echo '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />'
        echo '<meta name="viewport" content="width=device-width, initial-scale=1.0" />'
        printf '<link rel="stylesheet" href="%s" type="text/css" />\n' "${css_include[@]}"
        if [[ -z $global_feedburner ]]; then
            echo "<link rel=\"alternate\" type=\"application/rss+xml\" title=\"$template_subscribe_browser_button\" href=\"$blog_feed\" />"
        else 
            echo "<link rel=\"alternate\" type=\"application/rss+xml\" title=\"$template_subscribe_browser_button\" href=\"$global_feedburner\" />"
        fi
        } > ".header.html"
    fi
    # Add any excludes to the arguments array.
    if [[ "${settings[rsyncExcludes]}" != "" ]]; then
        rsyncArgs+=("--exclude \"${settings[rsyncExcludes]// /\" --exclude \"}\"")

    if [[ -f $footer_file ]]; then cp "$footer_file" .footer.html
    else {
        protected_mail=${global_email//@/&#64;}
        protected_mail=${protected_mail//./&#46;}
        echo "<div id=\"footer\">$global_license <a href=\"$global_author_url\">$global_author</a> &mdash; <a href=\"mailto:$protected_mail\">$protected_mail</a><br/>"
        echo 'Generated with <a href="https://github.com/cfenollosa/bashblog">bashblog</a>, a single bash script to easily create blogs like this one</div>'
        } >> ".footer.html"
    fi
    # Sync the files to the server with the given settings.
    eval "rsync ${rsyncArgs[*]} . ${settings[rsyncUser]}@${settings[rsyncAddress]}"
    # Postsync plugins
    run_plugins postsync
}

add_header() {
    local i
    # Find the next available post number
    local lastPost=0
    local postNumber=0
    for i in *."${settings[pageExtension]}" ; do
        lastPost=$(grep -m1 -- '<meta name="application-name" content=".*" data-postnumber=".*">$' "$i" 2> /dev/null | tr -cd '[:digit:]')
        if [[ $lastPost -gt $postNumber ]]; then
            postNumber=$lastPost
        fi
    done
    # Increment postNumber for the next available slot.
    ((postNumber++))
    # Heredocument left aligned
cat << EOF > "$htmlFile"
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="$scriptName">
<meta name="application-name" content="$scriptName" data-postnumber="$postNumber">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
  $( # Meta plugins.
  run_plugins meta "${fileName}")
<title>${settings[blogName]}</title>
<link rel="stylesheet" type="text/css" href="bashtml-css/${settings[css]}">
</head>
<body>
  $( # Pre header plugins.
  run_plugins preheader "${fileName}")
<header>
<h1><a href="${settings[blogURL]}">${settings[blogName]}</a></h1>
<p>
${settings[blogDescription]}
</p>
</header>
  $( # Post header plugins.
  run_plugins postheader "${fileName}")
<!-- END OF HEADER -->
EOF
    # Heredocument end
}

add_footer() {
    # Set license and author info
    local author
    local license
    if [[ -n "${settings[authorURL]}" ]]; then
        author="<a href=\"${settings[authorURL]}\">${settings[author]}</a>"
    else
        author="${settings[author]}"
# Delete the temporarily generated include files
delete_includes() {
    rm ".title.html" ".footer.html" ".header.html"
}

# Create the css file from scratch
create_css() {
    # To avoid overwriting manual changes. However it is recommended that
    # this function is modified if the user changes the blog.css file
    (( ${#css_include[@]} > 0 )) && return || css_include=('main.css' 'blog.css')
    if [[ ! -f blog.css ]]; then 
        # blog.css directives will be loaded after main.css and thus will prevail
        echo '#title{font-size: x-large;}
        a.ablack{color:black !important;}
        li{margin-bottom:8px;}
        ul,ol{margin-left:24px;margin-right:24px;}
        #all_posts{margin-top:24px;text-align:center;}
        .subtitle{font-size:small;margin:12px 0px;}
        .content p{margin-left:24px;margin-right:24px;}
        h1{margin-bottom:12px !important;}
        #description{font-size:large;margin-bottom:12px;}
        h3{margin-top:42px;margin-bottom:8px;}
        h4{margin-left:24px;margin-right:24px;}
        img{max-width:100%;}
        #twitter{line-height:20px;vertical-align:top;text-align:right;font-style:italic;color:#333;margin-top:24px;font-size:14px;}' > blog.css
    fi
    if [[ -n "${settings[licenseURL]}" ]]; then
        license="<a href=\"${settings[licenseURL]}\">${settings[license]}</a>"
    else
        license="${settings[license]}"

    # If there is a style.css from the parent page (i.e. some landing page)
    # then use it. This directive is here for compatibility with my own
    # home page. Feel free to edit it out, though it doesn't hurt
    if [[ -f ../style.css ]] && [[ ! -f main.css ]]; then
        ln -s "../style.css" "main.css" 
    elif [[ ! -f main.css ]]; then
        echo 'body{font-family:Georgia,"Times New Roman",Times,serif;margin:0;padding:0;background-color:#F3F3F3;}
        #divbodyholder{padding:5px;background-color:#DDD;width:100%;max-width:874px;margin:24px auto;}
        #divbody{border:solid 1px #ccc;background-color:#fff;padding:0px 48px 24px 48px;top:0;}
        .headerholder{background-color:#f9f9f9;border-top:solid 1px #ccc;border-left:solid 1px #ccc;border-right:solid 1px #ccc;}
        .header{width:100%;max-width:800px;margin:0px auto;padding-top:24px;padding-bottom:8px;}
        .content{margin-bottom:5%;}
        .nomargin{margin:0;}
        .description{margin-top:10px;border-top:solid 1px #666;padding:10px 0;}
        h3{font-size:20pt;width:100%;font-weight:bold;margin-top:32px;margin-bottom:0;}
        .clear{clear:both;}
        #footer{padding-top:10px;border-top:solid 1px #666;color:#333333;text-align:center;font-size:small;font-family:"Courier New","Courier",monospace;}
        a{text-decoration:none;color:#003366 !important;}
        a:visited{text-decoration:none;color:#336699 !important;}
        blockquote{background-color:#f9f9f9;border-left:solid 4px #e9e9e9;margin-left:12px;padding:12px 12px 12px 24px;}
        blockquote img{margin:12px 0px;}
        blockquote iframe{margin:12px 0px;}' > main.css
    fi
    # Heredocument left aligned
cat << EOF >> "$htmlFile"
  $( # Plugin placed just above footer.
    run_plugins prefooter "${fileName}")
<!-- START OF FOOTER -->
<footer>
  $( # Plugin placed inside footer.
    run_plugins footer "${fileName}")
<h3>$license $author</h3>
<p>
Powered by <a href="https://gitlab.com/stormdragon2976/bashtml">${scriptName} version ${scriptVersion}</a>
</p>
$( if [[ -n "${settings[email]}" ]]; then
echo "<p>"
echo "<script type=\"text/javascript\" src=\"bashtml-scripts/email.js\"></script>"
echo "<noscript>"
echo "Javascript is disabled. If you would like to contact ${settings[author]} via email, please turn on Javascript, or, run this string through base64 -d:<br>"
echo "${settings[email]}"
echo "</noscript>"
echo "</p>"
fi)
</footer>
  $( # Plugin placed just below footer.
    run_plugins postfooter "${fileName}")
</body>
</html>
EOF
    # Heredocument end
}

build_pages() {
    # Set the filename to index.ext so that plugins that depend on it will work.
    fileName="index.${settings[pageExtension]}"
    # Start the index file
    add_header "index"
    # Remove the post number from the index.
    # It is added during the header section.
    sed -i -- '/<meta name="application-name" content=".*" data-postnumber=".*">$/d' "$htmlFile"
    # Generate the index page
    local i
    local lastPost=1 # placeholder for last published postnumber
    local lastNumber=1 # Keep track of the last highest number.
    local pages # A list of pages to add to index.
    for i in *".${settings[pageExtension]}" ; do
        lastNumber=$(grep -m1 -- '<meta name="application-name" content=".*" data-postnumber=".*">$' "$i" | tr -cd '[:digit:]')
        lastNumber=${lastNumber:-0}
        if [[ $lastNumber -gt $lastPost ]]; then
            lastPost=$lastNumber
        fi
}

# Regenerates all the single post entries, keeping the post content but modifying
# the title, html structure, etc
rebuild_all_entries() {
    echo -n "Rebuilding all entries "

    for i in ./*.html; do
        is_boilerplate_file "$i" && continue;
        contentfile=.tmp.$RANDOM
        while [[ -f $contentfile ]]; do contentfile=.tmp.$RANDOM; done

        echo -n "."
        # Get the title and entry, and rebuild the html structure from scratch (divs, title, description...)
        title=$(get_post_title "$i")

        get_html_file_content 'text' 'text' <"$i" >> "$contentfile"

        # Read timestamp from post, if present, and sync file timestamp
        timestamp=$(awk '/<!-- '$date_inpost': .+ -->/ { print }' "$i" | cut -d '#' -f 2)
        [[ -n $timestamp ]] && touch -t "$timestamp" "$i"
        # Read timestamp from file in correct format for 'create_html_page'
        timestamp=$(LC_ALL=C date -r "$i" +"$date_format_full")

        create_html_page "$contentfile" "$i.rebuilt" no "$title" "$timestamp" "$(get_post_author "$i")"
        # keep the original timestamp!
        timestamp=$(LC_ALL=C date -r "$i" +"$date_format_timestamp")
        mv "$i.rebuilt" "$i"
        chmod 644 "$i"
        touch -t "$timestamp" "$i"
        rm "$contentfile"
    done
    # Now, lastNumber is repurposed to be the last number included on the index.
    if [[ $(($lastPost - ${settings[maxIndex]})) -le 0 ]]; then
        lastNumber=1
    echo ""
}

# Displays the help
usage() {
    echo "$global_software_name v$global_software_version"
    echo "Usage: $0 command [filename]"
    echo ""
    echo "Commands:"
    echo "    post [-html] [filename] insert a new blog post, or the filename of a draft to continue editing it"
    echo "                            it tries to use markdown by default, and falls back to HTML if it's not available."
    echo "                            use '-html' to override it and edit the post as HTML even when markdown is available"
    echo "    edit [-n|-f] [filename] edit an already published .html or .md file. **NEVER** edit manually a published .html file,"
    echo "                            always use this function as it keeps internal data and rebuilds the blog"
    echo "                            use '-n' to give the file a new name, if title was changed"
    echo "                            use '-f' to edit full html file, instead of just text part (also preserves name)"
    echo "    delete [filename]       deletes the post and rebuilds the blog"
    echo "    rebuild                 regenerates all the pages and posts, preserving the content of the entries"
    echo "    reset                   deletes everything except this script. Use with a lot of caution and back up first!"
    echo "    list                    list all posts"
    echo "    tags [-n]               list all tags in alphabetical order"
    echo "                            use '-n' to sort list by number of posts"
    echo ""
    echo "For more information please open $0 in a code editor and read the header and comments"
}

# Delete all generated content, leaving only this script
reset() {
    echo "Are you sure you want to delete all blog entries? Please write \"Yes, I am!\" "
    read -r line
    if [[ $line == "Yes, I am!" ]]; then
        rm .*.html ./*.html ./*.css ./*.rss &> /dev/null
        echo
        echo "Deleted all posts, stylesheets and feeds."
        echo "Kept your old '.backup.tar.gz' just in case, please delete it manually if needed."
    else
        lastNumber=$(($lastPost - ${settings[maxIndex]}))
        echo "Phew! You dodged a bullet there. Nothing was modified."
    fi
    # Generate the list of pages to be included on the index.
    for i in $(seq ${lastPost} -1 ${lastNumber}) ; do
        pages[${#pages[@]}]="$(grep -H "^<meta name=\"application-name\" content=\".*\" data-postnumber=\"$i\">$" *".${settings[pageExtension]}" | cut -d: -f1)"
    done
    # Build the actual index's posts.
    for i in "${pages[@]}" ; do
        sed -n -e '/^<!-- END OF HEADER -->$/,/<!-- START OF FOOTER -->$/p' "$i" | sed '/^<!-- \(END OF HEADER\|START OF FOOTER\) -->$/d' >> "$htmlFile"
    done
    # Decrement lastNumber, then see if it is greater than 0
    ((lastNumber--))
    if [[ $lastNumber -gt 0 ]]; then
        # Create links to older posts
        local articleFileName
        echo "<h6>Older Posts</h6>" >> "$htmlFile"
        echo "<p><ul>" >> "$htmlFile"
        for i in $(seq $lastNumber -1 1) ; do
            # This makes links to the older articles
            articleFileName="$(grep -H -- "^<meta name=\"application-name\" content=\".*\" data-postnumber=\"$i\">$" *.${settings[pageExtension]})"
            # Extract the file name by removing everything after the first :
            articleFileName="${articleFileName%%:*}"
            echo "<li><a href=\"$articleFileName\">$(grep -m1 '^<h2>.*</h2>$' "$articleFileName" | cut -d '>' -f3 | cut -d '<' -f1)</a></li>" >> "$htmlFile"
    call_plugins reset
}

# Detects if GNU date is installed
date_version_detect() {
	date --version >/dev/null 2>&1
	if (($? != 0));  then
		# date utility is BSD. Test if gdate is installed 
		if gdate --version >/dev/null 2>&1 ; then
            date() {
                gdate "$@"
            }
		else
            # BSD date
            date() {
                if [[ $1 == -r ]]; then
                    # Fall back to using stat for 'date -r'
                    format=${3//+/}
                    stat -f "%Sm" -t "$format" "$2"
                elif [[ $2 == --date* ]]; then
                    # convert between dates using BSD date syntax
                    command date -j -f "$date_format_full" "${2#--date=}" "$1" 
                else
                    # acceptable format for BSD date
                    command date -j "$@"
                fi
            }
        fi
    fi    
}

# Main function
# Encapsulated on its own function for readability purposes
#
# $1     command to run
# $2     file name of a draft to continue editing (optional)
do_main() {
    # Load any available plugins from plugins directory in current path or /usr/share/bashblog/plugins
    if [[ -d "${BASH_SOURCE[0]%/*}/plugins" ]]; then
        for f in "${BASH_SOURCE[0]%/*}/plugins/"*.sh ; do
            source "$f"
        done
        echo "</ul></p>" >> "$htmlFile"
    fi
    # Add the footer.
    add_footer "index"
    # Move indexpage into place
    cp -- "$htmlFile" "index.${settings[pageExtension]}"
}

new_post() {
    # create templet
    local templateText="$(echo -e "Title Goes Here\n\nArticle text here in markdown format.\n\nTags: optional, seperate, with, commas")"
    echo "$templateText" > "$mdFile"
    ${settings[editor]} "$mdFile"
    # compare the file with the template text and abandon if they are equal.
    if [[ "$(<"$mdFile")" == "$templateText" ]]; then
        echo "Post abandoned ."
        exit 0
    fi
    # Extract the title, the first line, to pass to plugins
    local title="$(head -1 "$mdFile" | sed 's/^[# ]*//')"
    # Page name is the title, with dashes instead of spaces, spaces compressed to only 1 at a time, and no punctuation.
    local pageName="$(echo "$title" | sed -e 's/^[[:space:]]\+//' -e 's/[[:space:]]\+$//' -e 's/[[:punct:]]//g' -e 's/[[:space:]]\+/-/g')"
    # Page names should also be completely lowercase.
    pageName="${pageName,,}"
    # Get the final file name to pass to plugins.
    fileName="${pageName}.${settings[pageExtension]}"
    # make sure the first line (title) is a heading level 2.
    sed -i -e "1s/\(.*\)/## [\1]($fileName)/" -e '1s/^#\+/##/' "$mdFile"
    # Add the header:
    add_header "$htmlFile"
    markdown "$mdFile" >> "$htmlFile"
    # Add the date. Note the html file is edited because it is created in the step above.
    # Slashes have to be escaped in html tags to not clash with sed. Of course I could have used something else like ; but I didn't.
    # Also, converted the title into a link to the page itself.
    sed -i "0,/<h2 id=\".*\">/{s/<h2 id=\".*\">\(.*\)<\/h2>$/<h2><a href=\"${pageName}.${settings[pageExtension]}\">\1<\/a><\/h2>\n<p>Posted $(date "+${settings[dateFormat]}") by ${settings[author]}<\/p>\n/}" "$htmlFile"
    # Create an array from the posts tags in the markdown file.
    # We need 2 sed statements, because the -e thing works on the whole input, not the previous result.
    local tags=($(sed -n 's/^Tags: \+\(.*\)/\1/p' "$mdFile" | sed 's/, */ /g'))
    if [[ ${#tags[@]} -ge 1 && -n "${settings[gnuSocialURL]}" ]]; then
        # Remove the tags line from the html file.
        # This needs to be the last occurrence, and I haven't found an easy solution to do this with sed.
        # So, I am thinking to use grep to get the last line number, then delete that line
        local i=$(grep -n "^<p>Tags: .*</p>$" "$htmlFile" | tail -1 | cut -d: -f1)
        sed -i "${i}d"  "$htmlFile"
        # Add tags back as links to the tags directory
        echo "<hr>" >> "$htmlFile"
        echo "<h4>Tags</h4>" >> "$htmlFile"
        echo "<p>" >> "$htmlFile"
        for i in "${tags[@]}" ; do
            echo "<a href=\"${settings[gnuSocialURL]}/search/notice?q=$i\">$i</a>," >> "$htmlFile"
    if [[ -d "/usr/share/bashblog/plugins" ]]; then
        for f in "/usr/share/bashblog/plugins/"*.sh ; do
            source "$f"
        done
        echo "</p>" >> "$htmlFile"
    fi
    # Add the footer:
    add_footer
    # Move files into place
    # Make sure a file of the same name does not exist already
    if [[ ! -e "${pageName}.${settings[pageExtension]}" ]]; then
        cp -- "$htmlFile" "${pageName}.${settings[pageExtension]}"
        build_pages
        echo "$title created successfully."
        # Plugins called after article is created.
        # Contains file name and page title.
        run_plugins post "${fileName}" "${title}"
    else
        echo "A file named ${pageName}.${settings[pageExtension]} already exists."
        echo "Your file is saved at ${htmlFile}. Please place it manually."
    # Get a list of all functions available.
    mapfile -t plugins < <(declare -F)
    # Loop through the function names and strip away stuff that is not needed.
    for i in "${!plugins[@]}" ; do
        plugins[i]="${plugins[i]#*f }"
        # Remove functions that do not start with plugin_
        if ! [[ "${plugins[i]}" =~ ^plugin_ ]]; then
            unset plugins[i]
        fi
    done
    # Detect if using BSD date or GNU date
    date_version_detect
    # Load default configuration, then override settings with the config file
    global_variables
    [[ -f $global_config ]] && source "$global_config" &> /dev/null 
    global_variables_check

    # Check for $EDITOR
    [[ -z $EDITOR ]] && 
        echo "Please set your \$EDITOR environment variable. For example, to use nano, add the line 'export EDITOR=nano' to your \$HOME/.bashrc file" && exit

    # Check for validity of argument including plugins
    LC_ALL=C type "plugin_command_$1" 2> /dev/null | grep -q "plugin_command_$1 is a function" && call_plugins command_$1
    [[ $1 != "reset" && $1 != "post" && $1 != "rebuild" && $1 != "list" && $1 != "edit" && $1 != "delete" && $1 != "tags" ]] && 
        usage && exit

    [[ $1 == list ]] &&
        list_posts && exit

    [[ $1 == tags ]] &&
        list_tags "$@" && exit

    if [[ $1 == edit ]]; then
        if (($# < 2)) || [[ ! -f ${!#} ]]; then
            echo "Please enter a valid .md or .html file to edit"
            exit
        fi
    fi
    if [[ ! -e "${pageName}.md" ]]; then
        cp -- "${mdFile}" "${pageName}.md"
    else
        echo "A file named ${pageName}.md already exists."
        echo "Your file is saved at ${mdFile}. Please place it manually."

    # Test for existing html files
    if ls ./*.html &> /dev/null; then
        # We're going to back up just in case
        tar -c -z -f ".backup.tar.gz" -- *.html &&
            chmod 600 ".backup.tar.gz"
    elif [[ $1 == rebuild ]]; then
        echo "Can't find any html files, nothing to rebuild"
        exit
    fi

    # Keep first backup of this day containing yesterday's version of the blog
    [[ ! -f .yesterday.tar.gz || $(date -r .yesterday.tar.gz +'%d') != "$(date +'%d')" ]] &&
        cp .backup.tar.gz .yesterday.tar.gz &> /dev/null

    [[ $1 == reset ]] &&
        reset && exit

    create_css
    create_includes
    [[ $1 == post ]] && write_entry "$@"
    [[ $1 == rebuild ]] && rebuild_all_entries && rebuild_tags
    [[ $1 == delete ]] && rm "$2" &> /dev/null && rebuild_tags
    if [[ $1 == edit ]]; then
        if [[ $2 == -n ]]; then
            edit "$3"
        elif [[ $2 == -f ]]; then
            edit "$3" full
        else
            edit "$2" keep
        fi
    fi
    rebuild_index
    all_posts
    all_tags
    make_rss
    delete_includes
}

rebuild_site() {
    echo "Rebuilding \"${settings[blogName]}\", please wait..."
    for mdFile in *.md ; do
        htmlFile="${mdFile%.md}.${settings[pageExtension]}"
        # Extract the title, the first line, to pass to plugins
        local title="$(head -1 "$mdFile" | sed 's/^[# ]*//')"
        # Page name is the title, with dashes instead of spaces, spaces compressed to only 1 at a time, and no punctuation.
        local pageName="$(echo "$title" | sed -e 's/^[[:space:]]\+//' -e 's/[[:space:]]\+$//' -e 's/[[:punct:]]//g' -e 's/[[:space:]]\+/-/g')"
        # Page names should also be completely lowercase.
        pageName="${pageName,,}"
        # Get the final file name to pass to plugins.
  fileName="${pageName}.${settings[pageExtension]}"
        # make sure the first line (title) is a heading level 2.
        sed -i -e "1s/\([^a-zA-Z0-9]*\)\(.*\)/## [\2]($fileName)/" -e '1s/^#\+/##/' "$mdFile"
        # Add the header:
        add_header "$htmlFile"
        markdown "$mdFile" >> "$htmlFile"
        # Add the date. Note the html file is edited because it is created in the step above.
        # Slashes have to be escaped in html tags to not clash with sed. Of course I could have used something else like ; but I didn't.
        # Also, converted the title into a link to the page itself.
        sed -i "0,/<h2 id=\".*\">/{s/<h2 id=\".*\">\(.*\)<\/h2>$/<h2><a href=\"${pageName}.${settings[pageExtension]}\">\1<\/a><\/h2>\n<p>Posted $(date "+${settings[dateFormat]}") by ${settings[author]}<\/p>\n/}" "$htmlFile"
        # Create an array from the posts tags in the markdown file.
        # We need 2 sed statements, because the -e thing works on the whole input, not the previous result.
        local tags=($(sed -n 's/^Tags: \+\(.*\)/\1/p' "$mdFile" | sed 's/, */ /g'))
        if [[ ${#tags[@]} -ge 1 && -n "${settings[gnuSocialURL]}" ]]; then
            # Remove the tags line from the html file.
            # This needs to be the last occurrence, and I haven't found an easy solution to do this with sed.
            # So, I am thinking to use grep to get the last line number, then delete that line
            local i=$(grep -n "^<p>Tags: .*</p>$" "$htmlFile" | tail -1 | cut -d: -f1)
            sed -i "${i}d"  "$htmlFile"
            # Add tags back as links to the tags directory
            echo "<hr>" >> "$htmlFile"
            echo "<h4>Tags</h4>" >> "$htmlFile"
            echo "<p>" >> "$htmlFile"
            for i in "${tags[@]}" ; do
                echo "<a href=\"${settings[gnuSocialURL]}/search/notice?q=$i\">$i</a>," >> "$htmlFile"
            done
            echo "</p>" >> "$htmlFile"

# Plugins
call_plugins() {
    local functionName="$1"
    shift
    for i in "${plugins[@]}" ; do
        if [[ "$i" =~ ^plugin_${functionName} ]]; then
            ${i} "$@"
        fi
        # Add the footer:
        add_footer
    done
    # make a temperary file for index.ext and markdown file.
    # This prevents removal of markdown file.
    htmlFile="$(mktemp -t html.XXXXXXXXXXXX)"
    mdFile="$(mktemp -t html.XXXXXXXXXXXX)"
    build_pages
}

# When the script closes, make sure everything is cleaned up.
trap cleanup EXIT
# Load user settings.
configuration
# Make sure directory structure and files exist.
init
# getopts does not take long arguments, so we have to convert them to short
for i in "$@"; do
    shift
    case "$i" in
        "--help") set -- "$@" "-h";;
        "--"new|post)   set -- "$@" "-p";;
        "--rebuild")   set -- "$@" "-r";;
        "--sync")   set -- "$@" "-s";;
        *)        set -- "$@" "$i"
    esac
done
# Short flags for recognized arguments along with what they do are in the commands array
# See the top of the file, where all global variables are declared.
# Because command is an array, we have to strip the spaces for getopts.
while getopts $(echo "${command[@]}" | tr -d '[:space:]') i ; do
    case "$i" in 
        h) show_help;;
        n|p) new_post;;
        s) sync_to_server;;
        r) rebuild_site;;
    esac
done
} 


#
# MAIN
# Do not change anything here. If you want to modify the code, edit do_main()
#
do_main "$@"

exit 0
# vim: set shiftwidth=4 tabstop=4 expandtab: