Full Code of selivan/thinclient for AI

master b3ff481270d0 cached
43 files
96.8 KB
27.1k tokens
1 requests
Download .txt
Repository: selivan/thinclient
Branch: master
Commit: b3ff481270d0
Files: 43
Total size: 96.8 KB

Directory structure:
gitextract_7s2hpa69/

├── .gitignore
├── LICENSE
├── README.md
├── Vagrantfile
├── build.sh
├── common/
│   └── apt/
│       └── sources.list
├── docs/
│   ├── BUILD.md
│   ├── DEPLOY.md
│   └── INTERNALS.md
├── extract-initrd.sh
├── extract-rootfs.sh
├── provision.inventory.ini
├── provision.yml
├── provision_server.yml
├── provision_template.yml
├── provision_template_freerdp.yml
├── provision_template_gui.yml
├── provision_template_vmware_horizon.yml
├── server/
│   ├── dnsmasq/
│   │   └── dnsmasq.conf
│   ├── nginx/
│   │   └── sites-available/
│   │       └── default
│   ├── pxelinux.cfg/
│   │   └── default
│   └── systemd/
│       └── system/
│           └── dnsmasq.service.d/
│               └── override.conf
├── template/
│   ├── apt/
│   │   └── apt.conf.d/
│   │       └── 10periodic
│   ├── home/
│   │   ├── .jwmrc
│   │   ├── .xinitrc
│   │   ├── bash_profile
│   │   ├── config/
│   │   │   └── autostart/
│   │   │       ├── autorun.desktop
│   │   │       ├── create-rdp-shortcuts.desktop
│   │   │       └── endless-run-vmware-view.desktop
│   │   └── local/
│   │       └── bin/
│   │           ├── autorun.sh
│   │           ├── create-rdp-shortcuts.sh
│   │           └── endless-run-vmware-view.sh
│   ├── initramfs-tools/
│   │   ├── hooks/
│   │   │   └── zz_custom
│   │   ├── initramfs.conf
│   │   └── scripts/
│   │       └── ram
│   ├── scripts/
│   │   ├── generate-interfaces.sh
│   │   ├── zram-start.sh
│   │   └── zram-stop.sh
│   ├── systemd/
│   │   └── system/
│   │       ├── generate-interfaces.service
│   │       ├── getty@tty1.service.d/
│   │       │   └── override.conf
│   │       └── zram.service
│   └── udev/
│       └── rules.d/
│           └── 10-my-media-automount.rules
└── vars.yml

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
# build images
build
# vagrant artifacts
.vagrant
*.log
# ansible artifacts
*.retry
# generated variables file for scripts
#vars.sh
# unpacked initrd and rootfs - for debug
unpacked-initrd
unpacked-rootfs

# VMWare Horizon
VMware-Horizon-Client-*.bundle



================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://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 <http://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
<http://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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
### Thinclient

Tools to create Ubuntu GNU/Linux image for [thin clients](http://en.wikipedia.org/wiki/Thin_client). It boots via network and works entirely from memory.

Supported Ubuntu version: 20.04 Focal Fossa (LTS release).

Doesn't need to mount root fileystem from network share, like [DisklessUbuntu](https://help.ubuntu.com/community/DisklessUbuntuHowto). Works much better in slow or unreliable networks: clients do not slow down or hang up because of network lags. Here is an [article](https://selivan.github.io/2018/03/08/ubuntu-based-thin-client.html) on how it works.

Most common use case is creating custom thin client for remote desktop, like RDP or VMWare Horizon.

This project was originaly created by [efim-a-efim](https://github.com/efim-a-efim).

### Features

* You can use ready templates for building FreeRDP or VMWare Horizon client, or build a clean console-only system and add whatever you need on top of it.
* Easily add any software from rich Ubuntu repositories: browser, photo/video recorder for camera, skype, media player, etc. This is not so easy for other thin clients, using their own package base, like [ThinStation](http://www.thinstation.org/).
* Overlays(file archives) can be mounted over root filesystem, allowing different workplaces to have different configs/software, without building many different images.
* Compressed RAM([Zram](https://en.wikipedia.org/wiki/Zram)) is used to make possible using on devices with low memory.

### Documentation

* [Build](docs/BUILD.md) - create and customize your own thinclient
* [Deploy](docs/DEPLOY.md) - bring it to production servers
* [Internals](docs/INTERNALS.md) - see how it ticks under the hood

### License

[GNU General Public License v3.0](LICENSE)

**P.S.** If this code is useful for you - don't forget to put a star on it's [github repo](https://github.com/selivan/thinclient).


================================================
FILE: Vagrantfile
================================================
# -*- mode: ruby -*-
# vi: set ft=ruby :

# For Ansible provisioning
Vagrant.require_version ">= 1.7.0"

Vagrant.configure("2") do |config|

  config.vm.box = "generic/ubuntu2004"
  # Disable automatic box update checking. If you disable this, then
  # boxes will only be checked for updates when the user runs
  # `vagrant box outdated`. This is not recommended.
  #config.vm.box_check_update = false

  # Machine to test images, boots from PXE
  # No autostart: useless without server to boot from
  config.vm.define "test", autostart: false do |machine|

      # Small size. It doesn't need disk anyway, no reason to lose disk space.
      machine.vm.box = "generic/alpine38"

      # Disable synced folders
      machine.vm.synced_folder ".", "/vagrant", disabled: true
      # Manual interface configuration
      machine.vm.provider "virtualbox" do |vb|
        # This is debug machine, we need to see the interface
        vb.gui = true
        vb.customize [
            "modifyvm", :id,
            "--boot1", "net",
            "--boot2", "none",
            "--boot3", "none",
            "--boot4", "none",
            "--nic1", "intnet",
            "--intnet1", "thinclient-pxc"
        ]
      end
  end

  # Machine to be template for images
  # Provisioning is mostly  done later by "server" machine
  config.vm.define "template" do |machine|

      machine.vm.synced_folder ".", "/vagrant"

      machine.vm.network "private_network", ip: "192.168.10.253", virtualbox__intnet: "thinclient-pxc"

      # Memory and CPU - to work faster with squashfs
      machine.vm.provider "virtualbox" do |vb|
        #vb.gui = true
        vb.memory = "2048"
        vb.cpus = 2
      end

  end

  # Machine to be used as PXC server and to configure others with ansible
  config.vm.define "server" do |machine|

      machine.vm.synced_folder ".", "/vagrant"

      machine.vm.network "private_network", ip: "192.168.10.254", virtualbox__intnet: "thinclient-pxc"

      # Does not require a lot of firepower to be a small TFTP/DHCP/HTTP server
      machine.vm.provider "virtualbox" do |vb|
        vb.memory = "512"
        vb.cpus = 1
      end

      machine.vm.provision "shell", inline: <<-SHELL
        type python3 || apt-get install -y python3-minimal
        type apt-add-repository || apt-get install -y software-properties-common
        apt-get install -y ansible
        mkdir -p /vagrant
      SHELL

      # Provision for all machines
      machine.vm.provision "ansible_local" do |ansible|
        # vagrant tries to install ansble from ppa that does not have version for ubuntu 20.04
        ansible.install = false
        ansible.verbose = true
        ansible.limit = "all"
        ansible.playbook = "provision.yml"
        ansible.inventory_path = "provision.inventory.ini"
      end

  end

end


================================================
FILE: build.sh
================================================
#!/bin/bash

build-kernel() {
    set -x
    vmlinuz_path=$(readlink -f /boot/vmlinuz)
    vmlinuz_filename=$(basename $vmlinuz_path)
    cp "$vmlinuz_path" "$buildddir"
    cd /vagrant/build
    chmod a+r "$vmlinuz_filename"
    ln -sf "$vmlinuz_filename" vmlinuz
    cd -
}

build-initrd() {
    set -x
    #update-initramfs -u
    initrd_path=$(readlink -f /boot/initrd.img)
    initrd_filename=$(basename $initrd_path)
    cp "$initrd_path" "$buildddir"
    cd "$buildddir"
    chmod a+r "$initrd_filename"
    ln -sf "$initrd_filename" initrd.img
    cd -
}

# UGLY CRUTCH HERE
# I coulnd't make mksquashfs exclude all files in some directory, but include the directory itself
# So let's generate list of all files to exclude explicitly
generate-rootfs-excludes() {
    # too much noise
    set +x
    for d in /boot /dev /proc /sys /tmp /var/tmp /run /mnt /home/vagrant /var/cache/apt /var/log /var/lib/apt/lists /usr/share/doc /usr/share/man /var/cache/man /usr/src /var/lib/systemd /var/lib/dhcp/; do
        find $d -mindepth 1 -maxdepth 1 >> "$1"
    done
    # Exclude all files from this packages
    for pkg in virtualbox-guest-utils grub-common grub-gfxpayload-lists grub-pc grub-pc-bin grub2-common; do
        dpkg -L $pkg | while read file; do
            if [ -f "$file" ]; then
                echo "$file" >> "$1"
            fi
        done
    done
    echo /vagrant >> "$1"
}

build-rootfs() {
    set -x
    mv "$buildddir"/rootfs.squashfs "$buildddir"/rootfs.squashfs.bak
    cd /
    generate-rootfs-excludes /tmp/rootfs.exclude_dirs
    echo "Backup /etc/fstab"
    mv /etc/fstab /etc/fstab.bak
    : > /etc/fstab
    mv /etc/localtime /etc/localtime.bak
    ln -fs /run/localtime /etc/localtime

    mksquashfs . /vagrant/build/rootfs.squashfs -no-xattrs -noappend -always-use-fragments -comp xz -ef /tmp/rootfs.exclude_dirs \
    && rm -f "$buildddir"/rootfs.squashfs.bak
    chmod a+r "$buildddir"/rootfs.squashfs

    # Restore interfaces file
    echo "Restore original /etc/fstab"
    # rm -f /etc/network/interfaces
    # mv /etc/network/interfaces.bak /etc/network/interfaces
    mv /etc/fstab.bak /etc/fstab
    rm -f /etc/localtime
    mv /etc/localtime.bak /etc/localtime
    cd -
}

build-home() {
    set -x
    mv "$buildddir"/home.tar.gz "$buildddir"/home.tar.gz.bak
    cd /home/vagrant
    # Don't use default unsecure ssh keys
    tar --exclude="./.ssh" -czf /vagrant/build/home.tar.gz ./ \
    && rm -f "$buildddir"/home.tar.gz.bak
    chmod a+r "$buildddir"/home.tar.gz
    cd -
}

buildddir=/vagrant/build

# should run thos script as root
if [ $(id -u) -ne 0 ]; then
    echo "Should run this scritp as root, trying sudo ..."
    sudo $0 "$@"
    exit $?
fi

case "$1" in
    all)
        build-kernel
        build-initrd
        build-rootfs
        build-home
        ;;
    kernel)
        build-kernel
        ;;
    initrd)
        build-initrd
        ;;
    rootfs)
        build-rootfs
        ;;
    home)
        build-home
        ;;
    *)
        echo "Usage: $0 all|initrd|kernel|rootfs|home"
        exit 1
        ;;
esac


================================================
FILE: common/apt/sources.list
================================================
deb http://archive.ubuntu.com/ubuntu/ {{ ansible_distribution_release }} main restricted
# deb-src http://archive.ubuntu.com/ubuntu/ {{ ansible_distribution_release }} main restricted

## Updates
deb http://archive.ubuntu.com/ubuntu/ {{ ansible_distribution_release }}-updates main restricted
# deb-src http://archive.ubuntu.com/ubuntu/ {{ ansible_distribution_release }}-updates main restricted

## Security
deb http://security.ubuntu.com/ubuntu {{ ansible_distribution_release }}-security main restricted
deb http://security.ubuntu.com/ubuntu {{ ansible_distribution_release }}-security universe
deb http://security.ubuntu.com/ubuntu {{ ansible_distribution_release }}-security multiverse
# deb-src http://security.ubuntu.com/ubuntu {{ ansible_distribution_release }}-security main restricted
# deb-src http://security.ubuntu.com/ubuntu {{ ansible_distribution_release }}-security universe
# deb-src http://security.ubuntu.com/ubuntu {{ ansible_distribution_release }}-security multiverse

## Universe
deb http://archive.ubuntu.com/ubuntu/ {{ ansible_distribution_release }} universe
deb http://archive.ubuntu.com/ubuntu/ {{ ansible_distribution_release }}-updates universe
# deb-src http://archive.ubuntu.com/ubuntu/ {{ ansible_distribution_release }} universe
# deb-src http://archive.ubuntu.com/ubuntu/ {{ ansible_distribution_release }}-updates universe

## Multiverse
deb http://archive.ubuntu.com/ubuntu/ {{ ansible_distribution_release }} multiverse
deb http://archive.ubuntu.com/ubuntu/ {{ ansible_distribution_release }}-updates multiverse
# deb-src http://archive.ubuntu.com/ubuntu/ {{ ansible_distribution_release }} multiverse
# deb-src http://archive.ubuntu.com/ubuntu/ {{ ansible_distribution_release }}-updates multiverse

## Backports
# deb http://archive.ubuntu.com/ubuntu/ {{ ansible_distribution_release }}-backports main restricted universe multiverse
# deb-src http://archive.ubuntu.com/ubuntu/ {{ ansible_distribution_release }}-backports main restricted universe multiverse

## Canonical's 'partner' repository.
# deb http://archive.canonical.com/ubuntu {{ ansible_distribution_release }} partner
# deb-src http://archive.canonical.com/ubuntu {{ ansible_distribution_release }} partner


================================================
FILE: docs/BUILD.md
================================================
You need [git](https://git-scm.com/), [Virtualbox](https://www.virtualbox.org) and [Vagrant](https://www.vagrantup.com/). You can use this software on any system: Windows, Linux or MacOS X.

## Prepare the workplace

Clone this repository:

```
git clone https://github.com/selivan/thinclient.git
cd thinclient
```

Create machine that will be used as template for our image. If you want to create minimal working image, set `install_gui_and_rdp_client:no` in `vars.yml`. If you are going to build an image for 32-bit hardware, set `config.vm.box` to `"ubuntu/xenial32"` in `Vagrantfile`.


`vagrant up template`

Create machine that will work as PXE server for testing. Also it is used to provision configuration to template machine with [Ansible](http://docs.ansible.com/ansible/latest/index.html).\
`vagrant up server`

Reload template to boot with new kernel.\
`vagrant reload template`

## Customize thin client image

Log into template machine.\
`vagrant ssh template`

Here you can customize your thin client image: install packages, configs, ...

Do not:

* Remove package virtualbox-guest-utils
* Remove openssh-server
* Change type and settings of first network interface

If you do one of this actions, then you should do further work inside template virtual machine manually, without vagrant.

After all work is done, build images inside template machine:

```bash
vagrant ssh template
cd /vagrant
./build.sh all
```

You will get this artifacts in `/vagrant/build` directory:

* `vmlinuz` - linux kernel
* `initrd.img` - initial ram disk
* `rootfs.squashfs` - root FS image
* `home.tar.gz` - compressed home directory for user ubuntu
* `pxelinux.0`, `ldlinux.c32` - [pxelinux](http://www.syslinux.org/wiki/index.php?title=PXELINUX) network bootloader files
* `pxelinux.cfg/default` - configuration for pxelinux. Boot parameters are set here.

Notice: ssh keys for ubuntu user, generated by Vagrant, are not included in home directory for security reasons.

## Test result

Create machine to test created images. It is configured to boot from server machine over network.
`vagrant up test`

Command will end up with error, it's OK: first interface is used for network boot, vagrant can not connect to it. After creating the test machine don't use `vagrant up` to launch it second time: Vagrant messes up custom configuration of first interface. Just run test machine from Virtualbox interface.

*Remove storage SCSI controller from test machine in Virtualbox. With my versions of linux kernel and virtualbox it sometimes makes kernel crash. Some rare bug, may not affect you.*

Server machine is cofigured as DHCP and TFTP server(dnsmasq), and HTTP server(nginx). HTTP is used to transfer huge rootfs image and home directory archive. In test environment you can transfer huge files with TFTP. But in real networks it is not very suitable for this task.

Start test machine. If everything is OK, it should boot with your image over network from server machine.

Shortcuts for connection to RDP servers are created from parameter `rdpservers` in `pxelinux.cfg`. It takes form\
`<server name 1>:<address>:<port>:<xfreerdp params>;<server name 2>:<address>:<port>:<xfreerdp params>`
xfreerdp parameters should be divided by `%` instead of spaces. Example:

```
rdpservers=dc1:dc1.example.net:3389;dc2:dc2.example.net:3390:/sec:rdp%/bpp:24
```

This will generate this two desktop shotucuts:

* dc1: `xfreerdp /workarea /f /v dc1.example.net:3389`
* dc2: `xfreerdp /workarea /f /v /sec:rdp /bpp:24 dc2.example.net:3390`

Check [freerdp documentation](https://github.com/FreeRDP/FreeRDP/wiki/CommandLineInterface) and `xfreerdp --help` for possible parameters.

## Overlays

It is possible to mount one or more file archives(*.tar.gz) over root filesystem. For example, you can add some software in `/opt` only for several workstations, without modifying the whole image.

Parameters in `pxelinux.cfg`:

```
overlayproto=http overlays=overlay1.tar.gz;overlay2.tar.gz
```

This will download `http://<pxe server ip>/overlay1.tar.gz` and `http://<pxe server ip>/overlay2.tar.gz` and mount them over root filesystem.

## Fallback mode for graphics

If your graphic card does not work good with video drivers, you can use uvesafb framebuffer mode as fallback. You should set desired screen resolution and color depth manually in boot parameters.

Parameters in `pxelinux.cfg`:

```
uvesafb=mode_option=1280x800-32;scroll=ywrap
```

Documentation on uvesafb:
* [kernel uvesafb.txt](https://www.kernel.org/doc/Documentation/fb/uvesafb.txt)
* [uvesafb in Arch wiki](https://wiki.archlinux.org/index.php/Uvesafb)


================================================
FILE: docs/DEPLOY.md
================================================
Step-by-setp setup instructions for remote boot server(dhcp+tftp) based on Ubuntu 16.04 Xenial. Two possible options: dnsmasq and dhcpd+tftpd.

Change IP addresses for your network. Place into ${TFTP_DIR} generated images: `vmlinuz`, `initrd.img`, `rootfs.squashfs`, `home.tar.gz`.

## DNSMASQ
[dnsmasq](http://www.thekelleys.org.uk/dnsmasq/doc.html) as all-on-one solution: DHCP and TFTP server.

```bash
THIS_SERVER_IP=192.168.10.254
SUBNET=192.168.10.0
NETMASK=255.255.255.0
ROUTER=192.168.10.254
DNS1=192.168.10.254
DNS2=192.168.10.254
DHCP_START=192.168.10.129
DHCP_END=192.168.10.253
TFTP_DIR=/var/lib/tftpboot

apt install dnsmasq syslinux-common pxelinux

mkdir -p "$TFTP_DIR"
cd "$TFTP_DIR"
ln -sf /usr/lib/syslinux/modules/bios/ldlinux.c32 ldlinux.c32
ln -sf /usr/lib/PXELINUX/pxelinux.0 pxelinux.0
mkdir pxelinux.cfg
cat > pxelinux.cfg/default <<EOF
default thinclient
prompt 0

# DEBUG with serial console
# console=tty1 console=ttyS0,115200n8
# DEBUG shell inside initrd
# initrddebug=y
# Mount overlays over rootfs
# overlayproto=http overlays=overlay1.tar.gz,overlay2.tar.gz
# Set compressed RAM (zram) disk size to specified percent of available RAM. Default is 50, 0 disables it.
# Documentation: https://www.kernel.org/doc/Documentation/blockdev/zram.txt
# zram_size_pct=50
# Fallback mode for graphics and framebuffer
# Documentation: https://www.kernel.org/doc/Documentation/fb/uvesafb.txt
# uvesafb=mode_option=1280x800-32;scroll=ywrap
label thinclient
    kernel vmlinuz
    append boot=ram initrd=initrd.img rootproto=http rooturl=/rootfs.squashfs homeproto=http homeurl=/home.tar.gz rdpservers=rdp%server1:dc1.example.net:3389;rdp%server2:dc2.example.net:5555:/sec:rdp%/bpp:24
EOF

cat > /etc/dnsmasq.conf <<EOF
# Do not run as DNS server
port=0

dhcp-range=${DHCP_START},${DHCP_END},${NETMASK}

# All available options: dnsmasq --help dhcp
dhcp-option=option:dns-server,${DNS1}
dhcp-option=option:dns-server,${DNS2}
dhcp-option=option:router,${ROUTER}
# If dnsmasq is providing a TFTP service (see --enable-tftp ) then only the filename is required here to enable network booting.
dhcp-boot=/pxelinux.0

# TFTP service
enable-tftp
tftp-root=${TFTP_DIR}
EOF

# Check config syntax
dnsmasq --test

systemctl restart dnsmasq.service
```

## DHCPD + TFTPD
[ISC DHCP Server](https://kb.isc.org/category/78/0/10/Software-Products/DHCP/) and [tftpd-hpa](http://git.kernel.org/cgit/network/tftp/tftp-hpa.git).

```bash
THIS_SERVER_IP=192.168.10.254
SUBNET=192.168.10.0
NETMASK=255.255.255.0
ROUTER=192.168.10.254
DNS1=192.168.10.254
DNS2=192.168.10.254
DHCP_START=192.168.10.129
DHCP_END=192.168.10.253
TFTP_DIR=/var/lib/tftpboot

apt install isc-dhcp-server tftpd-hpa syslinux-common pxelinux

mkdir -p "$TFTP_DIR"
cd "$TFTP_DIR"
# tftpd-hpa won't work with symlinks
cp -f /usr/lib/syslinux/modules/bios/ldlinux.c32 ldlinux.c32
cp -f /usr/lib/PXELINUX/pxelinux.0 pxelinux.0
mkdir pxelinux.cfg
cat > pxelinux.cfg/default <<EOF
default thinclient
prompt 0

# DEBUG with serial console
# console=tty1 console=ttyS0,115200n8
# DEBUG shell inside initrd
# initrddebug=y
# Mount overlays over rootfs
# overlayproto=http overlays=overlay1.tar.gz,overlay2.tar.gz
# Set compressed RAM (zram) disk size to specified percent of available RAM. Default is 50, 0 disables it.
# Documentation: https://www.kernel.org/doc/Documentation/blockdev/zram.txt
# zram_size_pct=50
# Fallback mode for graphics and framebuffer
# Documentation: https://www.kernel.org/doc/Documentation/fb/uvesafb.txt
# uvesafb=mode_option=1280x800-32;scroll=ywrap
label thinclient
    kernel vmlinuz
    append boot=ram initrd=initrd.img rootproto=http rooturl=/rootfs.squashfs homeproto=http homeurl=/home.tar.gz rdpservers=rdp%server1:dc1.example.net:3389;rdp%server2:dc2.example.net:5555:/sec:rdp%/bpp:24
EOF

cat > /etc/default/tftpd-hpa <<EOF

TFTP_USERNAME="tftp"
TFTP_DIRECTORY="${TFTP_DIR}"
TFTP_ADDRESS=":69"
TFTP_OPTIONS="--secure"
EOF

cat > /etc/dhcp/dhcpd.conf <<EOF
default-lease-time 600;
max-lease-time 7200;

subnet ${SUBNET} netmask ${NETMASK} {
  range ${DHCP_START} ${DHCP_END};
  option domain-name-servers ${DNS1}, ${DNS2};
  option subnet-mask ${NETMASK};
  option routers ${ROUTER};

  allow booting;
  #option option-128 code 128 = string;
  #option option-129 code 129 = text;
  next-server ${THIS_SERVER_IP};
  filename "pxelinux.0";
}
EOF

systemctl restart tftpd-hpa.service
systemctl restart isc-dhcp-server.service
```


================================================
FILE: docs/INTERNALS.md
================================================
Previous versions used chroot. To simplify things for end user, I swithed to Vagrant. You just configure normal virtual machine and run script to generate images. Also, this approach is closer to how system runs on real hardware.

## Provision

Server machine is used to provision both itself and template machine, because we don't want additional packages(ansible) inside image. But we have to install python2-minimal to make ansible work.

## Generating image

Some directories are excluded from rootfs image to make it more compact: `/boot`, `/usr/share/doc`, `/var/lib/apt/lists` and others, see `build.sh`.

## Network

Vagrant need static addresses in `/etc/network/interfaces`, so before generating image, it is replaced with symlink to `/tmp/interfaces`. After generating image it is moved back.

Auto-generated files in `/etc/network/interfaces.d` are appended to main interfaces file and removed.

File `/tmp/interfaces` is generated by special script, used as systemd service. It enables DHCP for all network interfaces found on the machine.

## Compressed RAM(zram)

Some diskless devices do not have enough memory to run all the applications you need. And they can't use swap. Linux kernel feature of RAM compressing([zram](https://www.kernel.org/doc/Documentation/blockdev/zram.txt)) may be helpful. It may be used by creating compressed RAM block devices and using them as SWAP partitions. For best performance number of devices should coinside with number of processor cores.

Boot parameter `zram_size_pct` controls what amount of available memory(in percent) will be used for zram. Default is 50. 0 disables this feature.

Scripts are copied from ubuntu [zram-config](https://packages.ubuntu.com/xenial/zram-config) package, the only change is configurable parameter for amount of memory used for zram and compression algorithm.

## Initrd hacks

initrd has custom boot script `ram` and hook to incude necessary binaries and modules. Script name is passed to kernel in boot parameters.

Overlays(optional) are mounted using [Overlayfs](https://en.wikipedia.org/wiki/OverlayFS). `/AUFS` helper directory is used to make it work.

Apparmor is removed, because it's profiles are not compatible with root FS mounted with Overlayfs.

## Debug

To look inside what you have built, helper scripts `extract-initrd.sh` and `extract-rootfs.sh` may be usen to extract generate initrd and rootfs to `unpacked-initrd` and `unpacked-rootfs` directories.

To get inside initrd shell, you may use boot parameter `initrddebug=y`.


================================================
FILE: extract-initrd.sh
================================================
#!/bin/bash

cd $(dirname $0)
mkdir -p ./unpacked-initrd
# Clean old files
find ./unpacked-initrd/ -mindepth 1 -depth -delete
cd unpacked-initrd
initrd=$(readlink -f ../build/initrd.img)
#cat "$initrd" | cpio -id
unmkinitramfs -v "$initrd" .
cd -


================================================
FILE: extract-rootfs.sh
================================================
#!/bin/bash

cd $(dirname $0)
# Clean old files
find ./unpacked-rootfs/ -mindepth 1 -depth -delete
rmdir ./unpacked-rootfs/
unsquashfs -d unpacked-rootfs build/rootfs.squashfs
cd -


================================================
FILE: provision.inventory.ini
================================================
[thinclient]
server ansible_connection=local

template ansible_ssh_host=192.168.10.253 ansible_ssh_user=vagrant ansible_ssh_private_key_file=/vagrant/.vagrant/machines/template/virtualbox/private_key

[thinclient:vars]
ansible_ssh_common_args="-o StrictHostKeyChecking=no -o ControlMaster=auto -o ControlPersist=60s -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes"


================================================
FILE: provision.yml
================================================
- hosts: server
  become: yes
  tasks:
    - name: read config variables
      include_vars: vars.yml
      # /vagrant path is used because ansible_local playbook runs inside virtual host
    - name: include provision_server.yml
      include_tasks: provision_server.yml
    # In VirtualBox on Windows files in shared /vagrant folder have too wide permissions
    # openssh refuses to use private keys with wrong mode
    - name: copy template ssh key to local directory and change its mode
      shell: cp -f /vagrant/.vagrant/machines/template/virtualbox/private_key /home/vagrant/template_private_key && chown vagrant /home/vagrant/template_private_key && chmod 0600 /home/vagrant/template_private_key
  handlers:
    - name: systemctl daemon-reload
      shell: systemctl daemon-reload
    - name: restart dnsmasq
      service: name=dnsmasq state=restarted
    - name: restart nginx
      service: name=nginx state=restarted

- hosts: template
  become: yes
  tasks:

  - name: read config variables
    include_vars: vars.yml
    tags: always

  - name: include provision_template.yml
    include_tasks: provision_template.yml

  - name: install GUI packages
    include_tasks: provision_template_gui.yml
    when: install_gui

  - name: install FreeRDP packages
    include_tasks: provision_template_freerdp.yml
    when: install_rdp_client

  - name: install GUI packages
    include_tasks: provision_template_vmware_horizon.yml
    when: install_vmware_horizon_client

  handlers:
    # update artifacts in build every time we need to regenerate initrd
    - name: update initramfs
      shell: update-initramfs -u && cd /vagrant && ./build.sh initrd
    - name: systemctl daemon-reload
      shell: systemctl daemon-reload
    - name: reload sshd
      service: name=sshd state=reloaded


================================================
FILE: provision_server.yml
================================================
- name: install apt sources.list
  template: src=common/apt/sources.list dest=/etc/apt/sources.list mode=0644 backup=yes
  register: apt_sources_list

- name: update apt cache
  apt: update_cache=yes
  when: apt_sources_list is changed

- name: install required packages
  apt:
    state: latest
    package:
      - dnsmasq
      - resolvconf # to manage /etc/resolv.conf
      - nginx-light
      - pxelinux
      # this package has modules necessary for pxelinux to boot
      - syslinux-common
      - rsync

- name: install some packages for convenient work
  apt:
    state: latest
    package:
      - bash-completion
      - tmux
      - mc
      - vim-tiny

- name: disable and stop systemd-resolved conflicting with dnsmasq
  service: name=systemd-resolved enabled=no state=stopped

# dnsmasq fails to start if tftp directory /vagrant/build is not ready yet
- name: create directory /vagrant/build
  file: path=/vagrant/build state=directory owner=vagrant group=vagrant mode=0755

- name: install dnsmasq configs
  template: src=server/dnsmasq/dnsmasq.conf dest=/etc/dnsmasq.conf mode=0644
  # dnsmasq fails to start if tftp directory /vagrant/build is not ready yet

# - name: create dnsmasq systemd config directories
#   file: path=/etc/systemd/system/dnsmasq.service.d state=directory recurse=yes

#   # try starting dnsmasq infinitely
# - name: install dnsmasq systemd config override
#   template: src=server/{{ item }} dest=/etc/{{ item }} mode=0640
#   with_items:
#     - systemd/system/dnsmasq.service.d/override.conf
#   notify: systemctl daemon-reload

- name: start dnsmasq service
  service: name=dnsmasq enabled=yes state=started

- name: create build directory
  file: path=/vagrant/build state=directory mode=0755

- name: copy pxelinux loader
  copy: src={{ item.src }} dest={{ item.dest }} remote_src=yes mode=0644
  loop:
    - { dest: '/vagrant/build/pxelinux.0', src: '/usr/lib/PXELINUX/pxelinux.0' }
    - { dest: '/vagrant/build/ldlinux.c32', src: '/usr/lib/syslinux/modules/bios/ldlinux.c32' }

- name: install nginx default site config
  template: src=server/nginx/sites-available/default dest=/etc/nginx/sites-available/default mode=0644
  notify: restart nginx

- name: enable nginx default site
  file: path=/etc/nginx/sites-enabled/default state=link src=/etc/nginx/sites-available/default
  notify: restart nginx

- name: create pxelinux.cfg directory
  file: path=/vagrant/build/pxelinux.cfg state=directory mode=0755

- name: copy pxelinux default configs
  copy: src=server/pxelinux.cfg/default dest=/vagrant/build/pxelinux.cfg/default mode=0644


================================================
FILE: provision_template.yml
================================================
- name: scripts to enable/disable zram
  template: src=template/scripts/{{ item }} dest=/usr/local/bin/{{ item }} mode=0755
  with_items:
    - zram-start.sh
    - zram-stop.sh

- name: systemd service to enable zram
  template: src=template/systemd/system/zram.service dest=/etc/systemd/system/zram.service mode=0644

- name: enable systemd service to enable zram
  service: name=zram.service enabled=yes

- name: install apt sources.list
  template: src=common/apt/sources.list dest=/etc/apt/sources.list mode=0644
  register: apt_sources_list

- name: update apt cache
  apt: update_cache=yes
  when: apt_sources_list is changed

- name: disable apt periodic update
  template: src=template/{{ item }} dest=/etc/{{ item }}
  with_items: [ apt/apt.conf.d/10periodic ]
# Apparmor profiles do not work with custom mounting scheme for rootfs

- name: remove apparmor and snapd
  apt:
    state: absent
    purge: yes
    package:
      - apparmor
      - snapd

- name: remove unnecessary packages
  apt: package="{{ packages_to_remove }}" state=absent purge=yes

- name: upgrade all packages
  apt:
    upgrade: dist

- name: remove dependencies that are no longer required
  apt:
    autoremove: yes

- name: disable sshd password login
  lineinfile: path=/etc/ssh/sshd_config regexp='^PasswordAuthentication' line='PasswordAuthentication no'
  notify: reload sshd

- name: install required packages
  apt: 
    state: latest
    package:
      - initramfs-tools
      - squashfs-tools
      # - aufs-tools
      - cpio
      # console autologin
      - mingetty
      # required for uvesafb framebuffer module
      # this package has built-in hooks for initramfs-tools
      - v86d

- name: remove virtual linux kernel packages and headers
  apt: 
    state: absent
    package:
      - linux-image-virtual
      - linux-headers-virtual

- name: install generic linux kernel and firmware packages
  apt: 
    state: latest
    package:
      - "{{ linux_kernel_package }}"
      - linux-firmware
      - amd64-microcode
      - intel-microcode

# We do not need old kernels and modules to take space in rootfs image
- name: remove old linux kernel and header packages
  shell: |
    export DEBIAN_FRONTEND=noninteractive
    dpkg -l 'linux-image-[0-9]*' | grep ^i | tr -s ' ' | cut -d' ' -f2 | sort -r | sed 1d  | xargs apt purge --allow-remove-essential -y
    dpkg -l 'linux-modules-[0-9]*' | grep ^i | tr -s ' ' | cut -d' ' -f2 | sort -r | sed 1d  | xargs apt purge --allow-remove-essential -y
    dpkg -l 'linux-modules-extra-[0-9]*' | grep ^i | tr -s ' ' | cut -d' ' -f2 | sort -r | sed 1d  | xargs apt purge --allow-remove-essential -y
    apt-get purge --allow-remove-essential -y 'linux-headers-*' 'linux-tools-*' 'linux-cloud-tools-*'

- name: install initramfs hook script and config
  copy: src=template/{{ item }} dest=/etc/{{ item }} mode=0755
  with_items:
    - initramfs-tools/hooks/zz_custom
    - initramfs-tools/scripts/ram
    - initramfs-tools/initramfs.conf
  notify: update initramfs
  register: initramfs_config
  tags: initramfs-conf

# This also may be done by handler, but if playbook fails at any step, handler doesn't start and we have initrd without boot script
- name: update initramfs
  shell: update-initramfs -u
  when: initramfs_config is changed

- name: create helper directory for aufs
  file: path=/AUFS state=directory mode=0755

- name: create config directory getty@tty1.service.d
  file: path=/etc/systemd/system/getty@tty1.service.d state=directory

- name: config autologin on first console
  template: src=template/{{ item }} dest=/etc/{{ item }} mode=0644
  with_items:
    - systemd/system/getty@tty1.service.d/override.conf
  notify: systemctl daemon-reload

- name: set password for autologin user to enable autologin
  user: name={{ autologin_user }} password={{ autologin_user | password_hash('sha512', 'salt') }}


================================================
FILE: provision_template_freerdp.yml
================================================
- name: add remmina and freerdp ppa repository
  apt_repository: repo="ppa:remmina-ppa-team/remmina-next"
  register: apt_repo_remmina
- name: update apt cache
  apt: update_cache=yes
  when: apt_repo_remmina is changed

- name: install freerdp
  apt: pkg={{ item }} state=latest install_recommends=no
  with_items:
    - freerdp-x11


================================================
FILE: provision_template_gui.yml
================================================
- name: intall gui packages
  apt: pkg={{ item }} state=latest install_recommends=no
  loop:
  - xserver-xorg-core
  - xserver-xorg-input-all
  # Basic universal video drivers
  - xserver-xorg-video-fbdev
  - xserver-xorg-video-vesa
  - xinit
  # sync time by NTP
  - ntpdate

- name: intall xorg video drivers
  apt:
    state: latest
    install_recommends: no
    package: "{{ xorg_video_drivers }}"

- name: install gui packages for lxde
  apt: pkg={{ item }} state=latest install_recommends=no
  loop:
  - lxde-core
  - lxde-common
  - lxde-icon-theme
  - lxsession
  - lxrandr
  - lxterminal
  when: gui_window_manager == 'lxde'

- name: install gui packages for jwm
  apt: pkg={{ item }} state=latest install_recommends=no
  loop:
    - jwm
    # includes xrandr
    - x11-xserver-utils
  when: gui_window_manager == 'jwm'

- name: remove dependencies that are no longer required
  apt:
    autoremove: yes

- name: install additional gui packages
  apt: pkg={{ item }} state=latest install_recommends=no
  with_items:
  - "{{ additional_gui_packages }}"

- name: user bash_profile to autostart X session on first console
  template: src=template/home/bash_profile dest=/home/{{ autologin_user }}/.bash_profile owner={{ autologin_user }} mode=0640

- name: user xinitrc
  template: src=template/home/.xinitrc dest=/home/{{ autologin_user }}/.xinitrc mode=0755 owner={{ autologin_user }}

# Docs: http://joewing.net/projects/jwm/config-2.3.html
- name: user jwmrc
  template: src=template/home/.jwmrc dest=/home/{{ autologin_user }}/.jwmrc mode=0644 owner={{ autologin_user }}

- name: user config directories
  file: path={{ item }} state=directory owner={{ autologin_user }}
  with_items:
    - /home/{{ autologin_user }}/.config
    - /home/{{ autologin_user }}/.config/autostart
    - /home/{{ autologin_user }}/.local
    - /home/{{ autologin_user }}/.local/bin

- name: user scripts
  template: src=template/home/local/bin/{{ item }} dest=/home/{{ autologin_user }}/.local/bin/{{ item }} owner={{ autologin_user }} mode=0755
  loop:
    - create-rdp-shortcuts.sh
    - endless-run-vmware-view.sh
    - autorun.sh

- name: autostart entries
  template: src=template/home/config/autostart/{{ item }} dest=/home/{{ autologin_user }}/.config/autostart/{{ item }} owner={{ autologin_user }} mode=0755
  loop:
    - create-rdp-shortcuts.desktop
    - autorun.desktop
    - endless-run-vmware-view.desktop


================================================
FILE: provision_template_vmware_horizon.yml
================================================
- name: install packages required for VMWare Horizon
  apt:
    state: present
    package: "{{ horizon_required_packages }}"

- name: download vmware horizon client bundle
  shell: "wget {{ horizon_url }}"
  args:
    chdir: /vagrant
    creates: "/vagrant/{{ horizon_bundle_file }}"

- name: install vmware horizon client
  shell: |
    chmod a+rx /vagrant/{{ horizon_bundle_file }} && \
    echo yes | /vagrant/{{ horizon_bundle_file }} {{ horizon_install_options }}
  args:
    chdir: /vagrant


================================================
FILE: server/dnsmasq/dnsmasq.conf
================================================
# 0 = no DNS server
port=53

# do not read /etc/resolv.conf
no-resolv

# use public dns servers
server=8.8.8.8
server=1.1.1.1
server=8.8.4.4

dhcp-range={{ dhcp_start_addr }},{{ dhcp_end_addr }},{{ dhcp_netmask }}

dhcp-option=option:router,{{ dhcp_router }}
# TFTP server name
dhcp-option=66,{{ dhcp_router }}
# If dnsmasq is providing a TFTP service (see --enable-tftp ) then only the filename is required here to enable network booting.
dhcp-boot=/pxelinux.0

# TFTP service
enable-tftp
tftp-root=/vagrant/build
# Without this, any file which is readable by the dnsmasq process under normal unix access-control rules is available via TFTP
#tftp-secure


================================================
FILE: server/nginx/sites-available/default
================================================
server {
      listen 80 default_server;
      server_name _;

      root /vagrant/build;

      location / {
              try_files $uri $uri/ =404;
      }
}


================================================
FILE: server/pxelinux.cfg/default
================================================
default thinclient
prompt 0

# Create shortcuts for RDP connections
# rdpservers=rdp%server%1:dc1.example.net:3389:/src:rdp;rdp%server2:dc2.example.net:5555:/sec:rdp%/bpp:24

# Endless run VMWare Horizon client with this options ( % changed to spaces )
# vmwareviewoptions=--fullscreen%--serverURL=192.168.10.254%--nonInteractive

# DEBUG with serial console
# console=tty1 console=ttyS0,115200n8
# DEBUG shell inside initrd
# initrddebug=y

# Mount overlays over rootfs
# overlayproto=http overlays=overlay1.tar.gz,overlay2.tar.gz

# Set compressed RAM (zram) disk size to specified percent of available RAM. Default is 50, 0 disables it.
# Documentation: https://www.kernel.org/doc/Documentation/blockdev/zram.txt
# zram_size_pct=50

# Fallback mode for graphics and framebuffer
# Documentation: https://www.kernel.org/doc/Documentation/fb/uvesafb.txt
# uvesafb=mode_option=1280x800-32;scroll=ywrap

# Set timezone, like Europe/Moscow
# Possible timezone files: /usr/share/zoneinfo
# timezone=Europe/Moscow

# List of ntp servers to sync time with, separated with comma
# ntpservers=0.ru.pool.ntp.org,1.ru.pool.ntp.org,2.ru.pool.ntp.org

# Time to shutdown, time format: man systemd.time
# Replace spaces with %
# shutdowntime=00:00:00

label thinclient
    kernel vmlinuz
    append boot=ram initrd=initrd.img rootproto=http rooturl=/rootfs.squashfs homeproto=http homeurl=/home.tar.gz rdpservers=rdp%server%1:dc1.example.net:3389:/sec:rdp vmwareviewoptions=--fullscreen%--serverURL=192.168.10.254 timezone=Europe/Moscow ntpservers=0.ru.pool.ntp.org,1.ru.pool.ntp.org,2.ru.pool.ntp.org shutdowntime=00:00:00


================================================
FILE: server/systemd/system/dnsmasq.service.d/override.conf
================================================
[Service]
Restart=always
RestartSec=1

[Unit]
# Disable start rate limiting
StartLimitInterval=0


================================================
FILE: template/apt/apt.conf.d/10periodic
================================================
# Disable periodic apt updates
APT::Periodic::Update-Package-Lists "0";
APT::Periodic::Enable "0";


================================================
FILE: template/home/.jwmrc
================================================
<?xml version="1.0"?>
<JWM>

    <!-- The root menu. -->
    <RootMenu onroot="12">
        <Include>/etc/jwm/debian-menu</Include>
        <Program icon="terminal.png" label="Terminal">xterm</Program>
        <Separator/>
        <Program icon="lock.png" label="Lock">
            xlock -mode blank
        </Program>
        <Separator/>
        <Restart label="Restart" icon="restart.png"/>
        <Exit label="Exit" confirm="true" icon="quit.png"/>
    </RootMenu>

    <!-- Options for program groups. -->
    <Group>
        <Option>tiled</Option>
        <Option>aerosnap</Option>
    </Group>
    <Group>
        <Class>Pidgin</Class>
        <Option>sticky</Option>
    </Group>
    <Group>
        <Name>xterm</Name>
        <Option>vmax</Option>
    </Group>
    <Group>
        <Name>xclock</Name>
        <Option>drag</Option>
        <Option>notitle</Option>
    </Group>

    <!-- Tray at the bottom. -->
    <Tray x="0" y="-1" height="25" autohide="off">

        <TrayButton icon="/usr/share/jwm/jwm-red.svg">root:1</TrayButton>
        <Spacer width="2"/>
        <TrayButton label="_">showdesktop</TrayButton>
        <Spacer width="2"/>

        <Pager labeled="true"/>

        <TaskList maxwidth="256"/>

        <Dock/>
        <Clock format="%H:%M"><Button mask="123">exec:xclock</Button></Clock>

    </Tray>

    <!-- Visual Styles -->
    <WindowStyle>
        <Font>Sans-9:bold</Font>
        <Width>4</Width>
        <Height>21</Height>
        <Corner>3</Corner>
        <Foreground>#FFFFFF</Foreground>
        <Background>#555555</Background>
        <Outline>#000000</Outline>
        <Opacity>0.5</Opacity>
        <Active>
            <Foreground>#FFFFFF</Foreground>
            <Background>#0077CC</Background>
            <Outline>#000000</Outline>
            <Opacity>1.0</Opacity>
        </Active>
    </WindowStyle>
    <TrayStyle group="true" list="all">
        <Font>Sans-9</Font>
        <Background>#333333</Background>
        <Foreground>#FFFFFF</Foreground>
        <Outline>#000000</Outline>
        <Opacity>0.75</Opacity>
    </TrayStyle>
    <TaskListStyle>
      <Font>Sans-9</Font>
      <Active>
        <Foreground>#FFFFFF</Foreground>
        <Background>#555555</Background>
      </Active>
      <Foreground>#FFFFFF</Foreground>
      <Background>#333333</Background>
    </TaskListStyle>
    <PagerStyle>
        <Outline>#000000</Outline>
        <Foreground>#555555</Foreground>
        <Background>#333333</Background>
        <Text>#FFFFFF</Text>
        <Active>
            <Foreground>#0077CC</Foreground>
            <Background>#004488</Background>
        </Active>
    </PagerStyle>
    <MenuStyle>
        <Font>Sans-9</Font>
        <Foreground>#FFFFFF</Foreground>
        <Background>#333333</Background>
        <Outline>#000000</Outline>
        <Active>
            <Foreground>#FFFFFF</Foreground>
            <Background>#0077CC</Background>
        </Active>
        <Opacity>0.85</Opacity>
    </MenuStyle>
    <PopupStyle>
        <Font>Sans-9</Font>
        <Foreground>#000000</Foreground>
        <Background>#999999</Background>
    </PopupStyle>

    <!-- Path where icons can be found.
         IconPath can be listed multiple times to allow searching
         for icons in multiple paths.
      -->
    <IconPath>/usr/share/icons/gnome/256x256/actions</IconPath>
    <IconPath>/usr/share/icons/gnome/256x256/apps</IconPath>
    <IconPath>/usr/share/icons/gnome/256x256/categories</IconPath>
    <IconPath>/usr/share/icons/gnome/256x256/devices</IconPath>
    <IconPath>/usr/share/icons/gnome/256x256/emblems</IconPath>
    <IconPath>/usr/share/icons/gnome/256x256/mimetypes</IconPath>
    <IconPath>/usr/share/icons/gnome/256x256/places</IconPath>
    <IconPath>/usr/share/icons/gnome/256x256/status</IconPath>
    <IconPath>/usr/share/icons/gnome/32x32/actions</IconPath>
    <IconPath>/usr/share/icons/gnome/32x32/animations</IconPath>
    <IconPath>/usr/share/icons/gnome/32x32/apps</IconPath>
    <IconPath>/usr/share/icons/gnome/32x32/categories</IconPath>
    <IconPath>/usr/share/icons/gnome/32x32/devices</IconPath>
    <IconPath>/usr/share/icons/gnome/32x32/emblems</IconPath>
    <IconPath>/usr/share/icons/gnome/32x32/mimetypes</IconPath>
    <IconPath>/usr/share/icons/gnome/32x32/places</IconPath>
    <IconPath>/usr/share/icons/gnome/32x32/status</IconPath>
    <IconPath>/usr/share/icons/gnome/scalable/actions</IconPath>
    <IconPath>/usr/share/icons/gnome/scalable/apps</IconPath>
    <IconPath>/usr/share/icons/gnome/scalable/categories</IconPath>
    <IconPath>/usr/share/icons/gnome/scalable/devices</IconPath>
    <IconPath>/usr/share/icons/gnome/scalable/emblems</IconPath>
    <IconPath>/usr/share/icons/gnome/scalable/mimetypes</IconPath>
    <IconPath>/usr/share/icons/gnome/scalable/places</IconPath>
    <IconPath>/usr/share/icons/gnome/scalable/status</IconPath>
    <IconPath>/usr/share/icons/hicolor/256x256/apps</IconPath>
    <IconPath>/usr/share/icons/hicolor/256x256/mimetypes</IconPath>
    <IconPath>/usr/share/icons/hicolor/32x32/actions</IconPath>
    <IconPath>/usr/share/icons/hicolor/32x32/apps</IconPath>
    <IconPath>/usr/share/icons/hicolor/32x32/categories</IconPath>
    <IconPath>/usr/share/icons/hicolor/32x32/devices</IconPath>
    <IconPath>/usr/share/icons/hicolor/32x32/emblems</IconPath>
    <IconPath>/usr/share/icons/hicolor/32x32/mimetypes</IconPath>
    <IconPath>/usr/share/icons/hicolor/32x32/status</IconPath>
    <IconPath>/usr/share/icons/hicolor/512x512/apps</IconPath>
    <IconPath>/usr/share/icons/hicolor/512x512/mimetypes</IconPath>
    <IconPath>/usr/share/icons/hicolor/scalable/actions</IconPath>
    <IconPath>/usr/share/icons/hicolor/scalable/apps</IconPath>
    <IconPath>/usr/share/icons/hicolor/scalable/categories</IconPath>
    <IconPath>/usr/share/icons/hicolor/scalable/devices</IconPath>
    <IconPath>/usr/share/icons/hicolor/scalable/emblems</IconPath>
    <IconPath>/usr/share/icons/hicolor/scalable/mimetypes</IconPath>
    <IconPath>/usr/share/icons/hicolor/scalable/places</IconPath>
    <IconPath>/usr/share/icons/hicolor/scalable/status</IconPath>
    <IconPath>/usr/share/icons</IconPath>
    <IconPath>/usr/share/pixmaps</IconPath>
    <IconPath>
        /usr/local/share/jwm
    </IconPath>

    <!-- Virtual Desktops -->
    <!-- Desktop tags can be contained within Desktops for desktop names. -->
    <Desktops width="1" height="1">
        <!-- Default background. Note that a Background tag can be
              contained within a Desktop tag to give a specific background
              for that desktop.
         -->
        <Background type="solid">#111111</Background>
    </Desktops>

    <!-- Double click speed (in milliseconds) -->
    <DoubleClickSpeed>400</DoubleClickSpeed>

    <!-- Double click delta (in pixels) -->
    <DoubleClickDelta>2</DoubleClickDelta>

    <!-- The focus model (sloppy or click) -->
    <FocusModel>sloppy</FocusModel>

    <!-- The snap mode (none, screen, or border) -->
    <SnapMode distance="10">border</SnapMode>

    <!-- The move mode (outline or opaque) -->
    <MoveMode>opaque</MoveMode>

    <!-- The resize mode (outline or opaque) -->
    <ResizeMode>opaque</ResizeMode>

    <!-- Key bindings -->
    <Key key="Up">up</Key>
    <Key key="Down">down</Key>
    <Key key="Right">right</Key>
    <Key key="Left">left</Key>
    <Key key="h">left</Key>
    <Key key="j">down</Key>
    <Key key="k">up</Key>
    <Key key="l">right</Key>
    <Key key="Return">select</Key>
    <Key key="Escape">escape</Key>

    <!-- <Key mask="A" key="Tab">nextstacked</Key> -->
    <!-- <Key mask="A" key="F4">close</Key> -->
    <!-- <Key mask="A" key="#">desktop#</Key> -->
    <!-- <Key mask="A" key="F1">root:1</Key> -->
    <!-- <Key mask="A" key="F2">window</Key> -->
    <!-- <Key mask="A" key="F10">maximize</Key> -->
    <!-- <Key mask="A" key="Right">rdesktop</Key> -->
    <!-- <Key mask="A" key="Left">ldesktop</Key> -->
    <!-- <Key mask="A" key="Up">udesktop</Key> -->
    <!-- <Key mask="A" key="Down">ddesktop</Key> -->

</JWM>


================================================
FILE: template/home/.xinitrc
================================================
#!/bin/sh
# global xinitrc: /etc/X11/xinit/xinitrc

{% if gui_window_manager == 'jwm' %}

{% if install_vmware_horizon_client %}
$HOME/.local/bin/autorun.sh &
$HOME/.local/bin/endless-run-vmware-view.sh &
{% endif %}

{% endif %}
# invoke global X session script
. /etc/X11/Xsession


================================================
FILE: template/home/bash_profile
================================================
# Autostart X session on first console
if [ -z "$DISPLAY" ] && [ "$XDG_VTNR" = "1" ]; then
    exec startx
fi


================================================
FILE: template/home/config/autostart/autorun.desktop
================================================
[Desktop Entry]
Name=autorun.sh
Exec=/home/vagrant/.local/bin/autorun.sh
Terminal=false
Type=Application


================================================
FILE: template/home/config/autostart/create-rdp-shortcuts.desktop
================================================
[Desktop Entry]
Name=Create RDP connections shortcuts
Exec=/home/vagrant/.local/bin/create-rdp-shortcuts.sh
Terminal=false
Type=Application


================================================
FILE: template/home/config/autostart/endless-run-vmware-view.desktop
================================================
[Desktop Entry]
Name=endless-run-vmware-view.sh
Exec=/home/vagrant/.local/bin/endless-run-vmware-view.sh
Terminal=false
Type=Application


================================================
FILE: template/home/local/bin/autorun.sh
================================================
#!/bin/bash
# Create shortcuts for RDP connections

ntp_timeout=5

{% if install_vmware_horizon_client %}

cat /proc/cmdline | tr ' ' '\n' | while read param; do
    if echo $param | grep -q '^timezone='; then
        timezone=$(echo $param | cut -d= -f2-)
        sudo ln -sf /usr/share/zoneinfo/"$timezone" /run/localtime
    fi
done

cat /proc/cmdline | tr ' ' '\n' | while read param; do
    if echo $param | grep -q '^shutdowntime='; then
        shutdowntime=$(echo $param | cut -d= -f2- | tr '%' ' ')
        sudo systemd-run --on-calendar="$shutdowntime" halt -p
    fi
done

cat /proc/cmdline | tr ' ' '\n' | while read param; do
    if echo $param | grep -q '^ntpservers='; then
        servers=$(echo $param | cut -d= -f2)
        echo $servers | tr ',' '\n' | while read srv; do
            # -u     Direct ntpdate to use an unprivileged port for outgoing packets
            # -t timeout  Specify the maximum time waiting for a server response as the
            # value timeout, in seconds and fraction
            echo "ntp server: $srv" >> /tmp/ntpdate.log
            ntpdate -u -t "$ntp_timeout" "$srv" >> /tmp/ntpdate.log 2>&1
            result=$?
            if [ $result -eq 0 ]; then
                break
            fi
        done
    fi
done

{% endif %}


================================================
FILE: template/home/local/bin/create-rdp-shortcuts.sh
================================================
#!/bin/bash
# Create shortcuts for RDP connections

desktop_dir="${XDG_DESKTOP_DIR:-$HOME/Desktop}"
default_options="/f"

# DEBUG
# echo "boot=ram rdpservers=MAIN:dc1.example.net:3389;BACKUP:dc2.example.net:3389:/sec:rdp%/bpp:24" \
cat /proc/cmdline \
| tr ' ' '\n' | while read param; do
    if echo $param | grep -q '^rdpservers='; then
        servers=$(echo $param | cut -d= -f2)
        echo $servers | tr ';' '\n' | while read srv; do
            srv_with_spaces=$(echo $srv | tr '%' ' ')
            name=$(echo $srv_with_spaces | cut -d':' -f1)
            addr=$(echo $srv_with_spaces | cut -d':' -f2)
            port=$(echo $srv_with_spaces | cut -d':' -f3)
            options=$(echo $srv_with_spaces | cut -d':' -f4-)

            exec="xfreerdp $default_options $options /v:$addr:$port"
            desktop_file="$desktop_dir/$name.desktop"

            echo -e "\nCreating $desktop_file:\n"
            echo "[Desktop Entry]" > "$desktop_file"
            echo "Name=$name" >> "$desktop_file"
            echo "Terminal=false" >> "$desktop_file"
            echo "Type=Application" >> "$desktop_file"
            echo "Icon=system" >> "$desktop_file"
            echo "Exec=$exec" >> "$desktop_file"
            # Desktop environment may display warning if desktop file is not executable
            chmod a+x "$desktop_file"
            cat "$desktop_file"
        done
    fi
done


================================================
FILE: template/home/local/bin/endless-run-vmware-view.sh
================================================
#!/bin/bash

cat /proc/cmdline | tr ' ' '\n' | while read param; do
    if echo $param | grep -q '^vmwareviewoptions='; then
        vmwareviewoptions_raw=$(echo $param | cut -d= -f2-)
        vmwareviewoptions=$(echo $vmwareviewoptions_raw | tr '%' ' ')
        while true; do
            vmware-view $vmwareviewoptions
            sleep 0.5
        done
    fi
done


================================================
FILE: template/initramfs-tools/hooks/zz_custom
================================================
#!/bin/sh

PREREQ=""

prereqs () {
	echo "${PREREQ}"
}

case "${1}" in
	prereqs)
		prereqs
		exit 0
		;;
esac

. /usr/share/initramfs-tools/hook-functions

copy_exec /usr/bin/atftp /bin
copy_exec /usr/bin/wget /bin
copy_exec /bin/tar /bin
copy_exec /bin/gunzip /bin

manual_add_modules squashfs
# Overlayfs
manual_add_modules overlay
# Fucking closed-source Intel(really it is PowerVR SGX) graphics with a lot of problems
#manual_add_modules cedarview_gfx
# Fallback mode for graphics
manual_add_modules uvesafb
# Required for uvasefb
copy_exec /sbin/v86d

exit 0


================================================
FILE: template/initramfs-tools/initramfs.conf
================================================
#
# initramfs.conf
# Configuration file for mkinitramfs(8). See initramfs.conf(5).
#
# Note that configuration options from this file can be overridden
# by config files in the /etc/initramfs-tools/conf.d directory.

#
# MODULES: [ most | netboot | dep | list ]
#
# most - Add most filesystem and all harddrive drivers.
#
# dep - Try and guess which modules to load.
#
# netboot - Add the base modules, network modules, but skip block devices.
#
# list - Only include modules from the 'additional modules' list
#

MODULES=most

#
# BUSYBOX: [ y | n | auto ]
#
# Use busybox shell and utilities.  If set to n, klibc utilities will be used.
# If set to auto (or unset), busybox will be used if installed and klibc will
# be used otherwise.
#

BUSYBOX=auto

#
# COMPCACHE_SIZE: [ "x K" | "x M" | "x G" | "x %" ]
#
# Amount of RAM to use for RAM-based compressed swap space.
#
# An empty value - compcache isn't used, or added to the initramfs at all.
# An integer and K (e.g. 65536 K) - use a number of kilobytes.
# An integer and M (e.g. 256 M) - use a number of megabytes.
# An integer and G (e.g. 1 G) - use a number of gigabytes.
# An integer and % (e.g. 50 %) - use a percentage of the amount of RAM.
#
# You can optionally install the compcache package to configure this setting
# via debconf and have userspace scripts to load and unload compcache.
#

COMPCACHE_SIZE=""

#
# COMPRESS: [ gzip | bzip2 | lzma | lzop | xz ]
#

COMPRESS=bzip2

#
# NFS Section of the config.
#

#
# DEVICE: ...
#
# Specify a specific network interface, like eth0
# Overridden by optional ip= bootarg
#

DEVICE=

#
# NFSROOT: [ auto | HOST:MOUNT ]
#

NFSROOT=auto


================================================
FILE: template/initramfs-tools/scripts/ram
================================================
#!/bin/sh

# configure_networking_custom(){
# 	interfaces=$(ip -o link | grep 'link/ether' | cut -d' ' -f2 | tr -d ':')
# 	for i in $interfaces; do
# 		# -1 Try to get a lease once. On failure exit with code 2.
# 		dhclient -v $i
# 	done
# }

get_url()
{
	_proto="$1"
	_url="$2"
	_dst="$3"
	_filename=`basename "${dst}"`

	case "${_proto}" in
	tftp)
		atftp --verbose --option "blksize 40960" -l "${_dst}" -r "${_url}" --no-source-port-checking -g "${ROOTSERVER}" 69
		return $?
	;;
	http)
		if echo ${_url} | grep -q '^http' ; then
			true
		else
			_url="http://${ROOTSERVER}/${_url}"
		fi
		wget -O "${_dst}" "${_url}"
		return $?
	;;
	esac
}

do_rammount()
{
	log_begin_msg "Downloading rootfs image ${rootproto} ${rooturl}"
	get_url "${rootproto}" "${rooturl}" "/tmp/rootfs.squashfs" || return $?
	log_end_msg

	set -x

	if [ -z "$overlays" ]; then

		echo "Mounting rootfs"
		mount -t squashfs -o loop '/tmp/rootfs.squashfs' "${rootmnt}" || return $?

	else

		echo "Mounting rootfs image to temp directory"
		mkdir -p /tmp/AUFS/rootfs
		mount -t squashfs -o loop '/tmp/rootfs.squashfs' /tmp/AUFS/rootfs || return $?

		# All lowerdirs for overlayfs
		lowerdirs=/tmp/AUFS/rootfs
		# All mountpoints that shoould be later moved inside real root
		mountpoints=rootfs

		echo "Processing overlays"
		for i in $overlays; do

			echo "Preparing"
			# XXXXXX is replaced with random digits and letters
			dir=$( mktemp -d -p /tmp/AUFS/ ovl_XXXXXX )
			dirname=${dir#/tmp/AUFS/}
			file=$( mktemp -p /tmp )

			echo "Downloading overlay $i"
			get_url "$overlayproto" "$i" $file || return $?

			echo "Extracting overlay $i to tmpfs"
			mount -t tmpfs none $dir
			gunzip -c $file | tar -x -C $dir -f- || return $?
			rm $file

			lowerdirs="${dir}:${lowerdirs}"
			mountpoints="$mountpoints ${dirname}"

		done

		echo "Mounting real root with overlayfs"
		mount -t overlay -o ro,lowerdir="$lowerdirs" none "${rootmnt}" || return $?

		echo "Creating tmpfs for moved mountpoints"
		mount -t tmpfs none "${rootmnt}"/AUFS || return $?

		echo "Moving mountpoints to directory in real root"
		for i in $mountpoints; do
			mkdir "${rootmnt}"/AUFS/"$i"
			mount --move /tmp/AUFS/"$i" "${rootmnt}"/AUFS/"$i" || return $?
		done

	fi

	# This parts in rootfs should be writable
	# /var/tmp - temporary files to be preserved between reboots(by FHS). Used by systemd-timesyncd
	# /var/lib/systemd - systemd timers and other auxiliary files
	# /var/lib/dhcp - reuqired to hold dhclient leases
	# /etc/apparmor.d/cache - required for apparmor cache. Apparmor doesn't play well with overlayfs root, this is in case I will ever fix it
	for dir in /tmp /var/tmp /run /media /var/log /var/lib/systemd /var/lib/dhcp /etc/apparmor.d/cache; do
		if [ -d "${rootmnt}${dir}" ]; then
			echo "Creating tmpfs rw filesystem for $dir"
			mount -t tmpfs none "${rootmnt}${dir}"
		fi
	done

	set +x

	# Home needs some magic 'cause it can be mounted through NFS
	# if [ "${homeproto}" = "nfs" ]; then
	# 	echo 'MOUNTING HOME WITH NFS'
	# 	echo "homeurl=${homeurl} ROOTPATH=${ROOTPATH} BOOTIF=${BOOTIF}"
	# 	#echo "Press Enter to continue"
	# 	#read enter
	# 	set -x
	# 	[ -z "${homeurl}" ] && [ "${ROOTPATH}" ] && homeurl=`dirname "${ROOTPATH}"`"/home/${BOOTIF}"
	# 	[ -z "${homeurl}" ] && homeurl=`dirname "${filename}"`"/home/${BOOTIF}"
	# 	[ -z `echo "${homeurl}" | grep ':'` ] && homeurl="${ROOTSERVER}:${homeurl}"
	# 	log_begin_msg "Mounting NFS home ${homeurl}"
	# 	nfsmount -o "nolock,rw,retrans=10" "${homeurl}" "${rootmnt}/vagrant" || return $?
	# 	#echo "Press Enter to continue"
	# 	#read enter
	# 	set +x
	# 	log_end_msg
	# else
	echo "Downloading home image ${homeproto} ${homeurl}"
	get_url "${homeproto}" "${homeurl}" "/tmp/home.tar.gz" || return $?

	echo "Mounting tmpfs to ${rootmnt}/home/vagrant"
	mount -t tmpfs -o size=${homesize:-512M} none ${rootmnt}/home || return $?

	mkdir -p ${rootmnt}/home/vagrant

	echo "Extracting home"
	gunzip -c '/tmp/home.tar.gz' | tar -x -C ${rootmnt}/home/vagrant -f- || return $?
	rm -f '/tmp/home.tar.gz'

	echo "do_rammount: OK"
	sleep 1
	return 0
}

mountroot()
{
		export homeproto='tftp'
		export rootproto='tftp'
		export rooturl=''
		export homeurl=''
		for x in $(cat /proc/cmdline); do
				case $x in
				rooturl=*)
						export rooturl=${x#rooturl=}
						;;
				homeurl=*)
						export homeurl=${x#homeurl=}
						;;
				homeproto=*)
						export homeproto=${x#homeproto=}
						;;
				overlays=*)
						overlays=${x#overlays=}
						export overlays=$( echo $overlays | tr ';' ' ' )
						;;
				uvesafb=*)
						uvesafb=${x#uvesafb=}
						export uvesafb=$( echo $uvesafb | tr ';' ' ' )
						;;
				overlayproto=*)
						export overlayproto=${x#overlayproto=}
						;;
				rootproto=*)
						export rootproto=${x#rootproto=}
						;;
				initrddebug=*)
						export initrddebug=${x#initrddebug=}
						;;
				esac
		done

		# Start debug shell inside initrd if initrddebug is set
		if [ -n "$initrddebug" ]; then
			echo "DEBUG shell inside initrd"
			sh
		fi

		echo "Loading module squashfs"
		modprobe squashfs
		# For DHCP
		echo "Loading module af_packet"
		modprobe af_packet

		# Fallback mode for graphics
		if [ -n "$uvesafb" ]; then
			echo "Configuring graphics with usavefb: $uvesafb"
			modprobe uvesafb $uvesafb
		fi

		# Networking
		# Default delay is around 180s
		delay=${ROOTDELAY:-180}

		# built-in from /scripts/functions
		configure_networking
		# configure_networking_custom

		do_rammount
		if [ $? -ne 0 ]; then
			# enable reboot on panic
			echo 1 > /proc/sys/kernel/panic
			# enable sysrq
			echo 1 > /proc/sys/kernel/sysrq
			echo "Something went wrong, rebooting in 15 seconds"
			sleep 15
			# trigger kernel panic
			echo c > /proc/sysrq-trigger
		fi
}


================================================
FILE: template/scripts/generate-interfaces.sh
================================================
#!/bin/bash
file=/tmp/interfaces

# Loopback
echo "auto lo" > "$file"
echo "iface lo inet loopback" >> "$file"
# All interfaces except loopback
ip link show | grep '^[0-9]' | cut -d' ' -f2 | grep -v 'lo:' | tr -d ':' | while read iface; do
    echo "auto $iface" >> "$file"
    echo "iface $iface inet dhcp" >> "$file"
done


================================================
FILE: template/scripts/zram-start.sh
================================================
#!/bin/sh

# load dependency modules
NRDEVICES=$(grep -c ^processor /proc/cpuinfo | sed 's/^0$/1/')
if modinfo zram | grep -q ' zram_num_devices:' 2>/dev/null; then
    MODPROBE_ARGS="zram_num_devices=${NRDEVICES}"
elif modinfo zram | grep -q ' num_devices:' 2>/dev/null; then
    MODPROBE_ARGS="num_devices=${NRDEVICES}"
else
    exit 1
fi
modprobe zram $MODPROBE_ARGS

for x in $(cat /proc/cmdline); do
    case $x in
    zram_size_pct=*)
        zram_size_pct=${x#zram_size_pct=}
        ;;
    esac
done

if [ -z "$zram_size_pct" ]; then export zram_size_pct=50; fi

if [ "$zram_size_pct" = "0" ]; then
    echo "zram usage disabled: zram_size_pct=0"
    exit 0
fi

# Calculate memory to use for zram (P percent of ram)
totalmem=`LC_ALL=C free | grep -e "^Mem:" | sed -e 's/^Mem: *//' -e 's/  *.*//'`
mem=$(((totalmem / 100 * ${zram_size_pct} / ${NRDEVICES}) * 1024))

# initialize the devices
for i in $(seq ${NRDEVICES}); do
    DEVNUMBER=$((i - 1))
    # Use lz4 algorithm if available
    grep -q lz4 /sys/block/zram${DEVNUMBER}/comp_algorithm && echo lz4 > /sys/block/zram${DEVNUMBER}/comp_algorithm
    echo $mem > /sys/block/zram${DEVNUMBER}/disksize
    mkswap /dev/zram${DEVNUMBER}
    swapon --priority 5 /dev/zram${DEVNUMBER}
done


================================================
FILE: template/scripts/zram-stop.sh
================================================
#!/bin/sh

if DEVICES=$(grep zram /proc/swaps | awk '{print $1}'); then
  for i in $DEVICES; do
    swapoff $i
  done
fi
rmmod zram


================================================
FILE: template/systemd/system/generate-interfaces.service
================================================
[Unit]
Description=Generate /tmp/interfaces file
Before=networking.service

[Install]
RequiredBy=networking.service

[Service]
Type=oneshot
ExecStart=/usr/local/bin/generate-interfaces.sh


================================================
FILE: template/systemd/system/getty@tty1.service.d/override.conf
================================================
[Service]
ExecStart=
ExecStart=-/sbin/mingetty --autologin {{ autologin_user }} --noclear %I


================================================
FILE: template/systemd/system/zram.service
================================================
[Unit]
Description=Initializes zram swaping

[Service]
ExecStart=/usr/local/bin/zram-start.sh
ExecStop=/usr/local/bin/zram-stop.sh
Type=oneshot
RemainAfterExit=true

[Install]
WantedBy=multi-user.target


================================================
FILE: template/udev/rules.d/10-my-media-automount.rules
================================================
# /etc/udev/rules.d/10-my-media-automount.rules
 
# start at sda (no system hard drive in live system)
KERNEL!="sd[a-z]*", GOTO="my_media_automount_end"
ACTION=="add", PROGRAM!="/sbin/blkid %N", GOTO="my_media_automount_end"
 
# import some useful filesystem info as variables
IMPORT{program}="/sbin/blkid -o udev -p %N"
 
# get the label if present, otherwise assign one based on device/partition
ENV{ID_FS_LABEL}!="", ENV{dir_name}="%E{ID_FS_LABEL}"
ENV{ID_FS_LABEL}=="", ENV{dir_name}="usbhd-%k"
 
# create the dir in /media and symlink it to /mnt
ACTION=="add", RUN+="/bin/mkdir -p '/media/%E{dir_name}'"
# create a symbolic link to /media/{usb_folder} on desktop
#ACTION=="add", RUN+="/bin/ln -s '/media/%E{dir_name}' '/home/aardvark/Desktop/%E{dir_name}'"
 
# global mount options
ACTION=="add", ENV{mount_options}="noatime"
# filesystem-specific mount options (777/666 dir/file perms for ntfs/vfat)
ACTION=="add", ENV{ID_FS_TYPE}=="vfat|ntfs", ENV{mount_options}="$env{mount_options},sync,dmask=000,fmask=111,utf8"
# automount ntfs filesystems using ntfs-3g driver
ACTION=="add", ENV{ID_FS_TYPE}=="ntfs", RUN+="/bin/mount -t ntfs-3g -o %E{mount_options} /dev/%k '/media/%E{dir_name}'"
# automount all other filesystems
ACTION=="add", ENV{ID_FS_TYPE}!="ntfs", RUN+="/bin/mount -t auto -o %E{mount_options} /dev/%k '/media/%E{dir_name}'"
 
# clean up after device removal
ACTION=="remove", ENV{dir_name}!="", RUN+="/bin/umount -l '/media/%E{dir_name}'", RUN+="/bin/rmdir '/media/%E{dir_name}'"
# remove dir in /media
ACTION=="remove", RUN+="/bin/rmdir '/media/%E{dir_name}'"
 
# exit
LABEL="my_media_automount_end"


================================================
FILE: vars.yml
================================================
# Choose "no" to create minimal console-only system
install_gui: yes

# Options: LXDE, jwm
gui_window_manager: jwm

install_rdp_client: no

install_vmware_horizon_client: yes

horizon_url: https://download3.vmware.com/software/view/viewclients/CART21FQ2/VMware-Horizon-Client-2006-8.0.0-16522670.x64.bundle
horizon_bundle_file: "{{ horizon_url | urlsplit('path') | basename }}"
# Docs: https://docs.vmware.com/en/VMware-Horizon-Client-for-Linux/2006/horizon-client-linux-installation/GUID-A5A6332F-1DEC-4D77-BD6E-1362596A2E76.html
horizon_install_options: >-
  --eulas-agreed --console --required
  --set-setting vmware-horizon-html5mmr html5mmrEnable yes
  --set-setting vmware-horizon-integrated-printing vmipEnable yes
  --set-setting vmware-horizon-media-provider mediaproviderEnable yes
  --set-setting vmware-horizon-mmr mmrEnable yes
  --set-setting vmware-horizon-rtav rtavEnable yes
  --set-setting vmware-horizon-scannerclient scannerEnable yes
  --set-setting vmware-horizon-serialportclient serialportEnable yes
  --set-setting vmware-horizon-smartcard smartcardEnable yes
  --set-setting vmware-horizon-tsdr tsdrEnable yes
  --set-setting vmware-horizon-usb usbEnable yes

horizon_required_packages:
  - libgtk-3-0
  - libcups2
  - libpcsclite1
  - libnss3

# Uncomment drivers for your devices
xorg_video_drivers:
# This will install all available drivers
  # - xserver-xorg-video-all
  # - xserver-xorg-video-all
  - xserver-xorg-video-intel
  # - xserver-xorg-video-nouveau
  # - xserver-xorg-video-amdgpu
  # - xserver-xorg-video-ati
  # - xserver-xorg-video-dummy
  # - xserver-xorg-video-geode
  # - xserver-xorg-video-mach64
  # - xserver-xorg-video-neomagic
  # - xserver-xorg-video-openchrome
  # - xserver-xorg-video-qxl
  # - xserver-xorg-video-r128
  # - xserver-xorg-video-radeon
  # - xserver-xorg-video-savage
  # - xserver-xorg-video-siliconmotion
  # - xserver-xorg-video-sisusb
  # - xserver-xorg-video-tdfx
  # - xserver-xorg-video-trident
  # - xserver-xorg-video-vmware

# Need something else?
additional_gui_packages: []

dhcp_start_addr: "192.168.10.129"
dhcp_end_addr: "192.168.10.250"
dhcp_netmask: "255.255.255.0"
dhcp_router: "192.168.10.254"

autologin_user: vagrant

# Linux kernel to install
linux_kernel_package: linux-image-generic

# Packages removed from template to make image smaller
packages_to_remove:
  - git
  - git-man
  - accountsservice
  - libaccountsservice0
  - multipath-tools
  - packagekit
  - packagekit-tools
  - apport
  - apport-symptoms
  - at
  - btrfs-tools
  - python3-apport
  - bcache-tools
  - byobu
  - cloud-init
  - cloud-guest-utils
  - cloud-initramfs-copymods
  - cloud-initramfs-dyn-netconf
  - cryptsetup
  - cryptsetup-bin
  - command-not-found
  - command-not-found-data
  - dosfstools
  - grub-legacy-ec2
  - info
  - lvm2
  - mdadm
  - language-pack-gnome-en
  - language-pack-gnome-en-base
  - language-pack-en
  - language-pack-en-base
  - lxc-common
  - lxcfs
  - lxd
  - lxd-client
  - mlocate
  - overlayroot
  - os-prober
  - pastebinit
  - rename
  - run-one
  - screen
  - tcpd
  - snapd
  - sosreport
  - ssh-import-id
  - ubuntu-core-launcher
  - ureadahead
  - unattended-upgrades
  - update-notifier-common
  - zerofree
  - update-manager-core
  - ubuntu-release-upgrader-core
  - python3-update-manager
  - python3-distupgrade
  - python3-cffi-backend
  - python3-cryptography
  - python3-json-pointer
  - python3-jsonpatch
  - python3-idna
  - python3-systemd
  - open-iscsi
  - open-vm-tools
  - vim
  - vim-runtime
  - vim-tiny
  - friendly-recovery
  - geoip-database
Download .txt
gitextract_7s2hpa69/

├── .gitignore
├── LICENSE
├── README.md
├── Vagrantfile
├── build.sh
├── common/
│   └── apt/
│       └── sources.list
├── docs/
│   ├── BUILD.md
│   ├── DEPLOY.md
│   └── INTERNALS.md
├── extract-initrd.sh
├── extract-rootfs.sh
├── provision.inventory.ini
├── provision.yml
├── provision_server.yml
├── provision_template.yml
├── provision_template_freerdp.yml
├── provision_template_gui.yml
├── provision_template_vmware_horizon.yml
├── server/
│   ├── dnsmasq/
│   │   └── dnsmasq.conf
│   ├── nginx/
│   │   └── sites-available/
│   │       └── default
│   ├── pxelinux.cfg/
│   │   └── default
│   └── systemd/
│       └── system/
│           └── dnsmasq.service.d/
│               └── override.conf
├── template/
│   ├── apt/
│   │   └── apt.conf.d/
│   │       └── 10periodic
│   ├── home/
│   │   ├── .jwmrc
│   │   ├── .xinitrc
│   │   ├── bash_profile
│   │   ├── config/
│   │   │   └── autostart/
│   │   │       ├── autorun.desktop
│   │   │       ├── create-rdp-shortcuts.desktop
│   │   │       └── endless-run-vmware-view.desktop
│   │   └── local/
│   │       └── bin/
│   │           ├── autorun.sh
│   │           ├── create-rdp-shortcuts.sh
│   │           └── endless-run-vmware-view.sh
│   ├── initramfs-tools/
│   │   ├── hooks/
│   │   │   └── zz_custom
│   │   ├── initramfs.conf
│   │   └── scripts/
│   │       └── ram
│   ├── scripts/
│   │   ├── generate-interfaces.sh
│   │   ├── zram-start.sh
│   │   └── zram-stop.sh
│   ├── systemd/
│   │   └── system/
│   │       ├── generate-interfaces.service
│   │       ├── getty@tty1.service.d/
│   │       │   └── override.conf
│   │       └── zram.service
│   └── udev/
│       └── rules.d/
│           └── 10-my-media-automount.rules
└── vars.yml
Condensed preview — 43 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (105K chars).
[
  {
    "path": ".gitignore",
    "chars": 255,
    "preview": "# build images\nbuild\n# vagrant artifacts\n.vagrant\n*.log\n# ansible artifacts\n*.retry\n# generated variables file for scrip"
  },
  {
    "path": "LICENSE",
    "chars": 35147,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 1880,
    "preview": "### Thinclient\n\nTools to create Ubuntu GNU/Linux image for [thin clients](http://en.wikipedia.org/wiki/Thin_client). It "
  },
  {
    "path": "Vagrantfile",
    "chars": 2824,
    "preview": "# -*- mode: ruby -*-\n# vi: set ft=ruby :\n\n# For Ansible provisioning\nVagrant.require_version \">= 1.7.0\"\n\nVagrant.configu"
  },
  {
    "path": "build.sh",
    "chars": 3088,
    "preview": "#!/bin/bash\n\nbuild-kernel() {\n    set -x\n    vmlinuz_path=$(readlink -f /boot/vmlinuz)\n    vmlinuz_filename=$(basename $"
  },
  {
    "path": "common/apt/sources.list",
    "chars": 2211,
    "preview": "deb http://archive.ubuntu.com/ubuntu/ {{ ansible_distribution_release }} main restricted\n# deb-src http://archive.ubuntu"
  },
  {
    "path": "docs/BUILD.md",
    "chars": 4612,
    "preview": "You need [git](https://git-scm.com/), [Virtualbox](https://www.virtualbox.org) and [Vagrant](https://www.vagrantup.com/)"
  },
  {
    "path": "docs/DEPLOY.md",
    "chars": 4426,
    "preview": "Step-by-setp setup instructions for remote boot server(dhcp+tftp) based on Ubuntu 16.04 Xenial. Two possible options: dn"
  },
  {
    "path": "docs/INTERNALS.md",
    "chars": 2531,
    "preview": "Previous versions used chroot. To simplify things for end user, I swithed to Vagrant. You just configure normal virtual "
  },
  {
    "path": "extract-initrd.sh",
    "chars": 247,
    "preview": "#!/bin/bash\n\ncd $(dirname $0)\nmkdir -p ./unpacked-initrd\n# Clean old files\nfind ./unpacked-initrd/ -mindepth 1 -depth -d"
  },
  {
    "path": "extract-rootfs.sh",
    "chars": 181,
    "preview": "#!/bin/bash\n\ncd $(dirname $0)\n# Clean old files\nfind ./unpacked-rootfs/ -mindepth 1 -depth -delete\nrmdir ./unpacked-root"
  },
  {
    "path": "provision.inventory.ini",
    "chars": 371,
    "preview": "[thinclient]\nserver ansible_connection=local\n\ntemplate ansible_ssh_host=192.168.10.253 ansible_ssh_user=vagrant ansible_"
  },
  {
    "path": "provision.yml",
    "chars": 1797,
    "preview": "- hosts: server\n  become: yes\n  tasks:\n    - name: read config variables\n      include_vars: vars.yml\n      # /vagrant p"
  },
  {
    "path": "provision_server.yml",
    "chars": 2590,
    "preview": "- name: install apt sources.list\n  template: src=common/apt/sources.list dest=/etc/apt/sources.list mode=0644 backup=yes"
  },
  {
    "path": "provision_template.yml",
    "chars": 3869,
    "preview": "- name: scripts to enable/disable zram\n  template: src=template/scripts/{{ item }} dest=/usr/local/bin/{{ item }} mode=0"
  },
  {
    "path": "provision_template_freerdp.yml",
    "chars": 334,
    "preview": "- name: add remmina and freerdp ppa repository\n  apt_repository: repo=\"ppa:remmina-ppa-team/remmina-next\"\n  register: ap"
  },
  {
    "path": "provision_template_gui.yml",
    "chars": 2411,
    "preview": "- name: intall gui packages\n  apt: pkg={{ item }} state=latest install_recommends=no\n  loop:\n  - xserver-xorg-core\n  - x"
  },
  {
    "path": "provision_template_vmware_horizon.yml",
    "chars": 498,
    "preview": "- name: install packages required for VMWare Horizon\n  apt:\n    state: present\n    package: \"{{ horizon_required_package"
  },
  {
    "path": "server/dnsmasq/dnsmasq.conf",
    "chars": 655,
    "preview": "# 0 = no DNS server\nport=53\n\n# do not read /etc/resolv.conf\nno-resolv\n\n# use public dns servers\nserver=8.8.8.8\nserver=1."
  },
  {
    "path": "server/nginx/sites-available/default",
    "chars": 161,
    "preview": "server {\n      listen 80 default_server;\n      server_name _;\n\n      root /vagrant/build;\n\n      location / {\n          "
  },
  {
    "path": "server/pxelinux.cfg/default",
    "chars": 1611,
    "preview": "default thinclient\nprompt 0\n\n# Create shortcuts for RDP connections\n# rdpservers=rdp%server%1:dc1.example.net:3389:/src:"
  },
  {
    "path": "server/systemd/system/dnsmasq.service.d/override.conf",
    "chars": 97,
    "preview": "[Service]\nRestart=always\nRestartSec=1\n\n[Unit]\n# Disable start rate limiting\nStartLimitInterval=0\n"
  },
  {
    "path": "template/apt/apt.conf.d/10periodic",
    "chars": 99,
    "preview": "# Disable periodic apt updates\nAPT::Periodic::Update-Package-Lists \"0\";\nAPT::Periodic::Enable \"0\";\n"
  },
  {
    "path": "template/home/.jwmrc",
    "chars": 8068,
    "preview": "<?xml version=\"1.0\"?>\n<JWM>\n\n    <!-- The root menu. -->\n    <RootMenu onroot=\"12\">\n        <Include>/etc/jwm/debian-men"
  },
  {
    "path": "template/home/.xinitrc",
    "chars": 283,
    "preview": "#!/bin/sh\n# global xinitrc: /etc/X11/xinit/xinitrc\n\n{% if gui_window_manager == 'jwm' %}\n\n{% if install_vmware_horizon_c"
  },
  {
    "path": "template/home/bash_profile",
    "chars": 110,
    "preview": "# Autostart X session on first console\nif [ -z \"$DISPLAY\" ] && [ \"$XDG_VTNR\" = \"1\" ]; then\n    exec startx\nfi\n"
  },
  {
    "path": "template/home/config/autostart/autorun.desktop",
    "chars": 105,
    "preview": "[Desktop Entry]\nName=autorun.sh\nExec=/home/vagrant/.local/bin/autorun.sh\nTerminal=false\nType=Application\n"
  },
  {
    "path": "template/home/config/autostart/create-rdp-shortcuts.desktop",
    "chars": 140,
    "preview": "[Desktop Entry]\nName=Create RDP connections shortcuts\nExec=/home/vagrant/.local/bin/create-rdp-shortcuts.sh\nTerminal=fal"
  },
  {
    "path": "template/home/config/autostart/endless-run-vmware-view.desktop",
    "chars": 137,
    "preview": "[Desktop Entry]\nName=endless-run-vmware-view.sh\nExec=/home/vagrant/.local/bin/endless-run-vmware-view.sh\nTerminal=false\n"
  },
  {
    "path": "template/home/local/bin/autorun.sh",
    "chars": 1282,
    "preview": "#!/bin/bash\n# Create shortcuts for RDP connections\n\nntp_timeout=5\n\n{% if install_vmware_horizon_client %}\n\ncat /proc/cmd"
  },
  {
    "path": "template/home/local/bin/create-rdp-shortcuts.sh",
    "chars": 1398,
    "preview": "#!/bin/bash\n# Create shortcuts for RDP connections\n\ndesktop_dir=\"${XDG_DESKTOP_DIR:-$HOME/Desktop}\"\ndefault_options=\"/f\""
  },
  {
    "path": "template/home/local/bin/endless-run-vmware-view.sh",
    "chars": 368,
    "preview": "#!/bin/bash\n\ncat /proc/cmdline | tr ' ' '\\n' | while read param; do\n    if echo $param | grep -q '^vmwareviewoptions='; "
  },
  {
    "path": "template/initramfs-tools/hooks/zz_custom",
    "chars": 564,
    "preview": "#!/bin/sh\n\nPREREQ=\"\"\n\nprereqs () {\n\techo \"${PREREQ}\"\n}\n\ncase \"${1}\" in\n\tprereqs)\n\t\tprereqs\n\t\texit 0\n\t\t;;\nesac\n\n. /usr/sh"
  },
  {
    "path": "template/initramfs-tools/initramfs.conf",
    "chars": 1646,
    "preview": "#\n# initramfs.conf\n# Configuration file for mkinitramfs(8). See initramfs.conf(5).\n#\n# Note that configuration options f"
  },
  {
    "path": "template/initramfs-tools/scripts/ram",
    "chars": 5729,
    "preview": "#!/bin/sh\n\n# configure_networking_custom(){\n# \tinterfaces=$(ip -o link | grep 'link/ether' | cut -d' ' -f2 | tr -d ':')\n"
  },
  {
    "path": "template/scripts/generate-interfaces.sh",
    "chars": 324,
    "preview": "#!/bin/bash\nfile=/tmp/interfaces\n\n# Loopback\necho \"auto lo\" > \"$file\"\necho \"iface lo inet loopback\" >> \"$file\"\n# All int"
  },
  {
    "path": "template/scripts/zram-start.sh",
    "chars": 1246,
    "preview": "#!/bin/sh\n\n# load dependency modules\nNRDEVICES=$(grep -c ^processor /proc/cpuinfo | sed 's/^0$/1/')\nif modinfo zram | gr"
  },
  {
    "path": "template/scripts/zram-stop.sh",
    "chars": 132,
    "preview": "#!/bin/sh\n\nif DEVICES=$(grep zram /proc/swaps | awk '{print $1}'); then\n  for i in $DEVICES; do\n    swapoff $i\n  done\nfi"
  },
  {
    "path": "template/systemd/system/generate-interfaces.service",
    "chars": 188,
    "preview": "[Unit]\nDescription=Generate /tmp/interfaces file\nBefore=networking.service\n\n[Install]\nRequiredBy=networking.service\n\n[Se"
  },
  {
    "path": "template/systemd/system/getty@tty1.service.d/override.conf",
    "chars": 93,
    "preview": "[Service]\nExecStart=\nExecStart=-/sbin/mingetty --autologin {{ autologin_user }} --noclear %I\n"
  },
  {
    "path": "template/systemd/system/zram.service",
    "chars": 203,
    "preview": "[Unit]\nDescription=Initializes zram swaping\n\n[Service]\nExecStart=/usr/local/bin/zram-start.sh\nExecStop=/usr/local/bin/zr"
  },
  {
    "path": "template/udev/rules.d/10-my-media-automount.rules",
    "chars": 1620,
    "preview": "# /etc/udev/rules.d/10-my-media-automount.rules\n \n# start at sda (no system hard drive in live system)\nKERNEL!=\"sd[a-z]*"
  },
  {
    "path": "vars.yml",
    "chars": 3570,
    "preview": "# Choose \"no\" to create minimal console-only system\ninstall_gui: yes\n\n# Options: LXDE, jwm\ngui_window_manager: jwm\n\ninst"
  }
]

About this extraction

This page contains the full source code of the selivan/thinclient GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 43 files (96.8 KB), approximately 27.1k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!