diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..12d2b60 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,22 @@ +root = true + +[*] +indent_style = space +insert_final_newline = true + +[*.{cmd,bat}] +end_of_line = crlf +indent_size = 4 + +[*.{ps1,psm1,psd1}] +end_of_line = crlf +indent_size = 4 +trim_trailing_whitespace = true + +[*.{ps1xml,props,xml.yaml,yml}] +indent_size = 2 + +[*.sh] +end_of_line = lf +indent_size = 2 + diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..b2d2c51 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,10 @@ +* text=auto + +*.ps1 text eol=crlf +*.psm1 text eol=crlf +*.psd1 text eol=crlf +*.cmd text eol=crlf +*.bat text eol=crlf + +*.sh text eol=lf + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a17cfee --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +tmp +tunic.exe + +*.ova diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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. + + + Copyright (C) + + 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 . + +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: + + Copyright (C) + 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 +. + + 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 +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..6f266c8 --- /dev/null +++ b/README.md @@ -0,0 +1,75 @@ +# Tunic + +Install Linux on Windows without a Live USB. + +The goal is a program that can install Linux on an existing Windows machine without need of a Live USB or making firmware/BIOS changes. + +## Status + +This project is pre-alpha quality. +We do not suggest you use on real hardware; use inside a virtual machine or on a computer you don't care about damaging. + +### Requirements + +* Windows 10, 64 bit +* Single unencrypted hard drive hosting the C: volume +* UEFI +* At least 4 GB RAM +* At least 15 GB of free disk space on C: +* Administrator user permissions +* Internet access + +### Limitations + +* Currently, Tunic only installs [Linux Mint with Cinnamon, 64 bit](https://blog.linuxmint.com/?p=3832). +* We are working on support for Windows 7 and 8, and other Debian/Ubuntu based Linux distros. +* There are no short term plans for MBR or 32 bit support. +* Error handling needs improvement. A failed install could leave the system in an undesirable state. + +### What Tunic Does + +1. Asks all questions at beginning +1. Offers full disk overwrite or dual boot arrangement. +1. If dual boot, shrink C: volume to make space for Linux. May require reboot. +1. Download the Linux .iso file +1. Install Grub with Secure Boot support +1. Reboot and run the Ubiquity installer, automated +1. Reboot into Linux! + +## Getting Started + +### Preparation + +Backup your data! + +Before you start, make sure to backup up your entire disk(s). +Tunic does not assist with full disk backup. +Read disclaimer for more information. + +### Usage + +1. Download and run the latest .exe file from releases. +1. Answer questions. +1. Let it run and walk away. It can take up to an hour. +1. Enjoy your new Linux OS! + +## More information + +See the docs directory for more information. + +## Legal Stuff + +### License + +Copyright (c) 2020 Michael Slattery. See commit history for list of other authors. + +Distributed under the [GNU General Public License, version 3](https://www.gnu.org/licenses/gpl-3.0.en.html). + +### Disclaimer + +This software could inadvertantly and permanently destroy all data, leave a computer unbootable, +or otherwise leave a computer in an undesirable state. +This software comes as-is with absolutely no warranty. +In no event shall shall the authors be held liable for damages arising out of use of this software. +Read sections [15, 16, and 17](https://www.gnu.org/licenses/gpl-3.0.en.html#section15) of the GNU GPL version 3 license for more information. + diff --git a/build.ps1 b/build.ps1 new file mode 100644 index 0000000..aec493a --- /dev/null +++ b/build.ps1 @@ -0,0 +1,89 @@ +# Windows build script + +# This is only for packaging a convenient, self-extracting .exe. +# tunic.ps1 is usable without packaging. + +# Install tools + +Set-StrictMode -version 1.0 +$ErrorActionPreference = 'Stop' + +mkdir -force tmp +$web = (New-Object System.Net.WebClient) + +if( ! (get-installedmodule -name ps2exe -errorAction silentlyContinue) ) { + install-packageprovider -name nuget -force + Install-Module -force -confirm:$false ps2exe +} + +if( ! ( Get-Command "7z" -ErrorAction SilentlyContinue ) ) { + if( ! ( Get-Command "choco" -ErrorAction SilentlyContinue ) ) { + iex $web.DownloadString('https://chocolatey.org/install.ps1') + } + choco install -y 7zip +} + +if( ! ( test-path "$PWD\tmp\7zSD.sfx" -errorAction SilentlyContinue) ) { + $web.downloadFile('https://www.7-zip.org/a/lzma1900.7z', "$PWD\tmp\lzma.7z") + 7z e "$PWD\tmp\lzma.7z" -otmp bin\7zSD.sfx +} + +#TODO: remove? +#$web = (New-Object System.Net.WebClient) +#iex $web.DownloadString('https://chocolatey.org/install.ps1') +#choco install -y nsis-advancedlogging +#$env:PATH += ";C:\Program Files (x86)\NSIS\Bin" + +function Test-Syntax +{ + [CmdletBinding(DefaultParameterSetName='File')] + param( + [Parameter(Mandatory=$true, ParameterSetName='File', Position = 0)] + [string]$Path, + + [Parameter(Mandatory=$true, ParameterSetName='String', Position = 0)] + [string]$Code + ) + + $Errors = @() + if($PSCmdlet.ParameterSetName -eq 'String'){ + [void][System.Management.Automation.Language.Parser]::` + ParseInput($Code,[ref]$null,[ref]$Errors) + } else { + [void][System.Management.Automation.Language.Parser]::` + ParseFile($Path,[ref]$null,[ref]$Errors) + } + + return [bool]($Errors.Count -lt 1) +} + +Test-Syntax 'tunic.ps1' + +# Clean + +Remove-Item tmp\lzma.7z -ErrorAction Ignore +Remove-Item tunic-script.exe -ErrorAction Ignore +Remove-Item tunic.exe -ErrorAction Ignore +Remove-Item tmp\tunic.7z -ErrorAction Ignore + +# Convert tunic.ps1 to tunic-script.exe + +invoke-ps2exe -inputfile tunic.ps1 -outputfile tunic-script.exe ` + -title Tunic ` + -credentialsGUI -requireAdmin ` + -noconsole -nooutput -noerror + +# Package self-extracting .exe + +7z a tmp\tunic.7z tunic.ps1 tunic-script.exe files\* + +gc -Encoding Byte -Path "tmp\7zSD.sfx","files\7z.conf","tmp\tunic.7z" ` + | sc -Encoding Byte tunic.exe + +copy tunic.exe ~\Desktop\tunic.exe + +# Clean + +Remove-Item tunic-script.exe -ErrorAction Ignore +Remove-Item tmp\tunic.7z -ErrorAction Ignore + diff --git a/doc/REFERENCES.md b/doc/REFERENCES.md new file mode 100644 index 0000000..c1b46b4 --- /dev/null +++ b/doc/REFERENCES.md @@ -0,0 +1,158 @@ +# Reseach and References + +## References + +### Backup and Recovery + +* https://www.howtogeek.com/167984/how-to-create-and-restore-system-image-backups-on-windows-8.1/ +* https://en.wikipedia.org/wiki/Comparison_of_disk_cloning_software +* http://odin-win.sourceforge.net/ +* http://www.invoke-ir.com/2015/06/ontheforensictrail-part3.html +* https://devblogs.microsoft.com/scripting/use-powershell-to-interact-with-the-windows-api-part-1/ +* https://code.msdn.microsoft.com/windowsapps/CCS-LABS-C-Low-Level-Disk-91676ca9 +* https://tuxboot.org/ + +### Cleanup + +* https://social.technet.microsoft.com/Forums/en-US/d053e005-c5fd-45bd-9bab-0379f31dba7a/how-to-set-the-no-paging-file-option-within-a-powershell-script?forum=ITCG +* https://stackoverflow.com/questions/37813441/powershell-script-to-set-the-size-of-pagefile-sys +* https://gallery.technet.microsoft.com/scriptcenter/Script-to-delete-System-4960775a +* https://superuser.com/a/1347749 +* https://www.tenforums.com/tutorials/4189-turn-off-fast-startup-windows-10-a.html +* https://windowsreport.com/delete-system-error-memory-dump-files-in-windows/ +* https://stackoverflow.com/questions/6035112/disable-application-crash-dumps-on-windows-7 + +### Install Linux + +* https://phoenixnap.dl.sourceforge.net/project/osboxes/v/vb/31-Lx-M-t/19.2/Cinnamon/19-2C-64bit.7z +* https://www.groovypost.com/howto/dual-boot-windows-10-linux/ +* https://www.dell.com/support/article/us/en/04/sln151664/how-to-install-ubuntu-linux-on-your-dell-pc + +### Downloads + +* https://github.com/unetbootin/unetbootin/blob/master/src/unetbootin/distrolst.cpp + +### ISO + +* https://askubuntu.com/questions/484434/install-ubuntu-without-cd-and-usb-how +* https://blogs.gnome.org/muelli/2016/08/remastering-a-custom-ubuntu-auto-install-iso/ +* https://github.com/core-process/linux-unattended-installation/ + +### VM + +* https://www.perkin.org.uk/posts/create-virtualbox-vm-from-the-command-line.html +* https://www.oracle.com/technical-resources/articles/it-infrastructure/admin-manage-vbox-cli.html +* https://www.virtualbox.org/ticket/8760 - locking +* https://www.howtogeek.com/213145/how-to%C2%A0convert-a-physical-windows-or-linux-pc-to-a-virtual-machine/ggj +* https://app.vagrantup.com/Microsoft/boxes/EdgeOnWindows10 +* https://github.com/samrocketman/vagrant-windows/blob/master/windows10/Vagrantfile +* https://www.vagrantup.com/docs/provisioning/shell.html + +### Testing and Support + +* https://www.microsoft.com/en-us/download/details.aspx?id=8002 - XP +* https://www.makeuseof.com/tag/download-windows-xp-for-free-and-legally-straight-from-microsoft-si/ + +### Boot Menu + +#### Repartitioning + +* http://www.smorgasbork.com/2019/04/23/fedora-windows-10-dual-boot-on-dell-inspiron/ +* https://docs.microsoft.com/en-us/powershell/module/bitlocker/suspend-bitlocker?view=win10-ps + +#### Swap file +* https://serverfault.com/questions/558069/use-wmi-to-remove-a-page-file +* https://www.c-sharpcorner.com/Blogs/disk-cleanup-using-powershell-scripts + +#### MBR + +* https://www.linuxquestions.org/questions/linux-general-1/using-bcdedit-to-configure-a-multiboot-system-and-add-linux-4175644308/ +* https://wiki.archlinux.org/index.php/Dual_boot_with_Windows/SafeBoot +* https://docs.microsoft.com/en-us/windows/deployment/mbr-to-gpt + +#### EFI + +* https://docs.microsoft.com/en-us/windows-hardware/manufacture/desktop/windows-and-gpt-faq +* https://wiki.archlinux.org/index.php/EFI_system_partition +* https://forums.linuxmint.com/viewtopic.php?t=300030 +* https://askubuntu.com/questions/342365/what-is-the-difference-between-grubx64-and-shimx64 +* https://wiki.archlinux.org/index.php/EFI_system_partition +* https://docs.microsoft.com/en-us/windows-hardware/manufacture/desktop/bcd-system-store-settings-for-uefi +* http://www.rodsbooks.com/linux-uefi/ +* https://neosmart.net/wiki/bcdedit/ +* https://askubuntu.com/questions/831216/how-can-i-reinstall-grub-to-the-efi-partition +* https://www.codeproject.com/Articles/833655/Modify-Windows-BCD-using-Powershell + +### Automated Install + +#### Ubiquity + +* https://code.launchpad.net/ubiquity +* https://wiki.ubuntu.com/UbiquityAutomation +* https://github.com/linuxmint/ubiquity/blob/master/d-i/source/preseed/debian/file-preseed.postinst +* https://github.com/linuxmint/ubiquity/blob/master/bin/ubiquity +* https://github.com/linuxmint/ubiquity/blob/master/d-i/source/preseed/preseed.sh + +#### Preseeding + +* https://www.leifove.com/2016/11/fully-automated-linux-mint-desktop.html +* https://help.ubuntu.com/lts/installation-guide/armhf/apbs02.html +* https://askubuntu.com/questions/1002043/how-to-an-unattended-installation-of-ubuntu-16-04-on-a-disk-with-existing-os +* https://github.com/core-process/linux-unattended-installation/tree/master/ubuntu/18.04/custom +* https://www.leifove.com/2016/11/fully-automated-linux-mint-desktop.html +* https://debian-handbook.info/browse/stable/sect.automated-installation.html +* https://help.ubuntu.com/lts/installation-guide/example-preseed.txt +* https://www.debian.org/releases/stable/example-preseed.txt +* https://www.packer.io/guides/automatic-operating-system-installs/preseed_ubuntu.html +* https://askubuntu.com/questions/457528/how-do-i-create-an-efi-bootable-iso-of-a-customized-version-of-ubuntu +* https://askubuntu.com/questions/806820/how-do-i-create-a-completely-unattended-install-of-ubuntu-desktop-16-04-1-lts +* https://github.com/hvanderlaan/ubuntu-unattended +* https://wikitech.wikimedia.org/wiki/PartMan +* https://wikitech.wikimedia.org/wiki/PartMan/Auto +* https://github.com/xpeppers/provisioning-example +* https://wiki.ubuntu.com/Enterprise/WorkstationAutoinstallPreseed +* https://help.ubuntu.com/lts/installation-guide/amd64/apbs04.html#preseed-partman + +### Keyboard +* https://github.com/linuxmint/ubiquity/blob/master/ubiquity/misc.py#L672 +* https://wiki.archlinux.org/index.php/Linux_console/Keyboard_configuration +* https://github.com/alexriss/keyboard-layout-converter + +#### Kickstart + +* https://help.ubuntu.com/community/KickstartCompatibility +* http://gyk.lt/ubuntu-16-04-desktop-unattended-installation/ + +#### Migration + +* https://git.launchpad.net/ubiquity/tree/ubiquity/plugins/ubi-migrationassistant.py?id=251afaeba2ee760267bd0253d24ffa6b668239a2 + +### Post Install + +These are things that can be used after the install for better integration between the partitions. + +* https://www.glump.net/howto/desktop/seamless-remote-linux-desktop-in-windows +* https://www.reddit.com/r/linuxquestions/comments/e964o5/way_to_reboot_to_windows_from_within_linux/ + +### Powershell + +* https://ss64.com/ps/syntax-elevate.html + +#### GUI +* https://theitbros.com/powershell-gui-for-scripts/ +* https://lazyadmin.nl/powershell/powershell-gui-howto-get-started/ +* https://poshgui.com/Editor +* https://github.com/MScholtes/PS2EXE +* https://stackoverflow.com/questions/21607593/powershell-form-layout + +#### 7Zip +* https://superuser.com/questions/42788/is-it-possible-to-execute-a-file-after-extraction-from-a-7-zip-self-extracting-a#42792 +* https://github.com/CommitteeOfZero/lzma-sdk/blob/master/DOC/installer.txt +* https://www.7-zip.org/download.html + +#### Timezone +* https://github.com/mj1856/TimeZoneConverter +* https://dejanstojanovic.net/aspnet/2018/july/differences-in-time-zones-in-net-core-on-windows-and-linux-host-os/ +* https://github.com/unicode-org/cldr/blob/master/common/supplemental/windowsZones.xml +* http://www.unicode.org/cldr/charts/latest/supplemental/zone_tzid.html + diff --git a/doc/TODO.md b/doc/TODO.md new file mode 100644 index 0000000..c008dda --- /dev/null +++ b/doc/TODO.md @@ -0,0 +1,187 @@ +# Roadmap and TODOs + +## Goals + +* As easily and as robustly as possible, convert a standard Windows system +to dual boot with Linux without the need for a USB drive or firmware changes. +* Linux to be configured the same as Windows with similar applications. + +## Technology + +This is subject to change over time. + +* Runs from Windows as exe file +* Written in Powershell and Python +* YAML configured + +## Versions + +### MVP + +* Opinionated, limited, non-robust +* Requires: Powershell 1.0, Win 10 64bit, Single OS(win), single disk, C:, EFI +* Installs: Dual boot, Linux Mint 64bit w/Cinnamon +* Auto-Configure basics: user account, locale, lang +* No support: XP/7/8, MBR, Bitlocker, AD, 32bit, LVM +* Run as exe as administrator (ps2exe) + +### MVP 2 + +* Add Support: Other Ubuntu variants, Full disk, MBR convertion +* Port config: wifi passwords, locale, Chrome/Firefox settings +* Limited efi backup/restore/revert functionality. before.cfg, after.cfg + +### 1.0 + +* Add support: Windows 7/8, MBR, flexible partitioning, 32 bit Windows, Bitlocker, Full disk +* Choice of several Debian/Ubuntu based distros +* Port settings and apps +* Plugins and flexible configuration to make it easy for others to help +* Buttons to go to web sites for help: google search, ubuntu support +* LVM and/or partition util? +* Programming Language change? +* Desktop icons: efi recover, OS in VM, reboot, browse files +* VirtualBox Linux host runs Windows partition w/sync protections. +* Reboot and continue without user intervention of password during install +* Keyboard layout preseed/import +* Tunic welcome app + +## Other Possible Use Cases and sub-components + +### Windows + +* Import apps from Windows to OSS Windows +* Cleanup disk +* Install Linux in a VM +* Full convert from Windows to Linux +* Install existing Linux partition as VM +* Uninstall Linux dual boot +* Install WSL to partition. +* Run Linux in file on ntfs/ext4 loopback + +### Windows and Linux + +* EFI/Grub/boot menu restore or repair +* Make persistent USB +* Shrink/Split/merge/move partitions. +* Shrink windows/expand Linux +* Backup/Restore MBR/EFI +* Make Live USB +* Live USB with multiple distros + +### Linux + +* Convert Windows Partition to VM and delete from grub/nvram +* Distro hop switcher +* Import settings/apps from Windows to Linux +* Remove Windows +* Install Windows after Linux +* Install another Linux distro over current. +* Convert to LVM +* Fast EFI boot (fwbootmgr -> Linux kernel w/ ext4 efi driver) +* Decimate Windows. Delete all except user files, defrag. + +### Far Future +* Allow secure boot. Detect if supportable. +* Support for: Windows Vista/XP, 32bit w/MBR, MBR +* AD domain login +* Fully remove Windows with option to convert to VM +* Minimal distro default if <=2GB. +* Non-debian distros. +* Distro switcher. Add multiple distros into menu. +* Assist with backup +* Warnings/help for known problematic hardware +* MacOS to Elementary OS + +## TODOs + +### Development + +#### Short-term Challenges +* Disable swap without reboot + +### Medium term challenges +* Auto-Resume from reboot + +#### Long Term Challenges +* Install powershell if not available +* Help with backup/clone + +#### Testing setup +* Vagrant +* Linux host. Possible WSL/Cygwin support. +* Download ISO and place in a cache directory. + +### Documentation +* Plugins how-to +* contribute.md +* support +* how to write a ticket: .log file + +#### Contributing doc +* Work in branch +* Suggest: ticket first with "thumbs up" from me. +* Follow standards + +#### standards +* .editorconfig +* lint check +* grub syntax checker + +### User Warnings and Errors + +#### Checks + +* Administrator +* enough space +* 64 bit +* Not on battery +* EFI/GPT/MBR, no secure boot +* Windows 10 +* Powershell libs available +* Command line apps available +* Bitlocker +* Compatibility (some day) + +#### Warnings + +* Backup +* Upgrade firmware +* Disable secure boot +* Might brick your machine +* Limited support + +#### Uninstallers + +* grub.cfg + initrd.lz - Undo installation (up to this point) + +#### Compatibility Warnings + +* NVidia + +## Support and Testing + +### Manual Testing + +* MBR vs EFI +* Test on Windows 7 +* Bitlocker +* Secure boot + +### Automated Testing +* VirtualBox in VirtualBox. Nested VBox only supports 32bit OSes +* Download VMs from Microsoft +* Install apps in Windows +* Cache file downloads (option) +* Scenarios: MBR/EFI, Win 7/10 +* Scripted. +* Limit phases. Use snapshots for start phase. + +## Basic Flow +1. Clean +2. Create new parition +3. Copy ISO to partition (not including MBR) +4. Modify ISO partition to include seed files +5. Copy grub files to efi partition +6. Reboot to Linux + diff --git a/doc/junk/allow.ps1 b/doc/junk/allow.ps1 new file mode 100644 index 0000000..74c0a68 --- /dev/null +++ b/doc/junk/allow.ps1 @@ -0,0 +1,3 @@ +# Usage . .\allow.ps1 +Set-ExecutionPolicy Bypass -Scope Process -Force + diff --git a/doc/junk/clean.ps1 b/doc/junk/clean.ps1 new file mode 100644 index 0000000..0a1aeb2 --- /dev/null +++ b/doc/junk/clean.ps1 @@ -0,0 +1,44 @@ +# Turn off swap +Write-Host "Cleaning file system..." + +$letter = $env:HOMEDRIVE[0] + +# Turn off hibernation and fast start +REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Power" /V HiberbootEnabled /T REG_DWORD /D 0 /F +powercfg.exe /h off + +# Diable swap +$computersys = Get-WmiObject Win32_ComputerSystem -EnableAllPrivileges +$computersys.AutomaticManagedPagefile = $False +$computersys.Put() +#TODO: failed: wmic pagefile delete + +$pagefile = Get-WmiObject -Query "Select * From Win32_PageFileSetting Where Name like '%pagefile.sys'" +$pagefile.InitialSize = 0 +$pagefile.MaximumSize = 0 +$pagefile.Put() +#ALT: delete or move pagefile.sys +#ALT: wmic computersystem set AutomaticManagedPagefile=False +#ALT: wmic pagefileset where name="C:\\pagefile.sys" delete + +# Cleanup +start-process Cleanmgr /sagerun:16 -wait +#TODO: Get-ComputerRestorePoint | Delete-ComputerRestorePoint -WhatIf +Disable-ComputerRestore -Drive "C:\" +fsutil usn deletejournal /d /n c: +vssadmin delete shadows /all /quiet +#TODO: remove: Dism /Online /Cleanup-Image /StartComponentCleanup /ResetBase +Disable-WindowsErrorReporting +#Clear-WindowsDiagnosticData -Force + +#TODO: REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\CrashControl" /V CrashDumpEnabled /T REG_DWORD /D 0 /F +#TODO: REG ADD "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\Windows Error Reporting" /v Disabled /T REG_DWORD /D 1 /F + +# Defrag +Write-Host "Defragmenting disk..." +Optimize-Volume -DriveLetter $letter -ReTrim -Defrag -SlabConsolidate -TierOptimize -NormalPriority + +# Reboot is necessary before swap can be deleted. +#TODO: reboot and continue w/o password +Restart-Computer + diff --git a/doc/junk/garbage.txt b/doc/junk/garbage.txt new file mode 100644 index 0000000..bdadb1b --- /dev/null +++ b/doc/junk/garbage.txt @@ -0,0 +1,577 @@ +This file is for brain-storming. It's full of junk and garbage. +WINDOWS TO LINUX + +architecture: + powershell with System.Windows.Forms + powershell core for Linux. MVP GUI pattern. + powershell as DSL for config + bundle as exe with elevated privs + monkeypatching by plugins to fix issues. + Automated testing + Can't really do this until we have pre-MVP + Test hardware uses HDD + Triggered by push to master + Everything will be set up to use an http proxy that will cache downloads. + Start with full drive image backup, and separate C: partition image backup. + Create report of config of partitions and bootmgr + Windows script runs on boot. + Waits for network trigger to start install. + Auto start script downloads current code and runs it with default settings. + Any error or warning is recorded. + At end, reboot to Linux + Linux post-install script + chroot into tmpfs file system + repartition C: + linux back to original + recover backup image to partition + Inject auto-run script + Change boot manager to original + verify partiion table and bootmgr is idential to start + reboot + +documentation: + plugins: how to write a plugin, include external repos. + contribute: rules, licensing, todo, roadmap + manually.md: how to install manually + reference.md: research and background. + manually.md: how to do everything it does on the command line, with links and images. + support.md + include .log file + partition table + systeminfo + boot menu entries. bcdedit /list + errors + virtualbox VM report + hyper-v status, if any + readme.md: + support and disclaimers + + + +repositories: + - https://github.com/user/project +winfs: /mnt/ntfs +distros: + # Only Ubuntu-based distros allowed + ubuntu: + description: ... + iso: ... + xubuntu: + debian: + mint: + name: Linux Mint with Cinnamon + iso: + xmint: + name: Linux Mint with Xfce +importers: + wine: + vm: + +RootPlugins: + - ScannerPlugin + + + + + +----- + +name: base +description: Required by all other plugins +priority: 0 +packages: [git,ansible,pip,snap] +status: hidden,always + + +name: Pictures +usercopy: [Pictures, Documents, Videos] + +name: MozillaMaintenanceService +match: 'Mozilla Maintenance Service' +status: ignore + +----- + +# Core properties. +name: git-bash +is_ok_dupliate: false +status: disabled # disable,always,ignore,backup,primary,hidden. + # Must be installed. Similar + # backup=don't install if a dup is available + # primary=don't install any dups. This is best fit. + # hidden=do not show in the list of apps. auto-select. +time: 12 # Estimated minutes to install +# Plugin properites +match: #file path, or registry, or app name pattern + - "$PROGRAMFILE/git" +match-script: | + ... +wine: [] +# Always install, even if a duplicate. +match-expr: "python-expression" +duplicate-of: [git] +packages: [git] +snaps: [] +pip: [] +copyhome: [.ssh, .gitconfig, .gitignore] +#copy: ["from:to"] # if dest not in $HOME, root:root 644 +# Variables for scripts. populated by UIs +environment: + name: 'value' +pre-install: 'bash' +post-install: | + #!/bin/bash + if [ -f ~/.ssh/idrsa ]; then chmod 600 ~/.ssh/idrsa; fi +form: +#http://docs.yafowil.info/yaml.html +ansible: + ... + + +* Ask: + - I already have Linux installed in a partition + - I Only have Windows installed. + - This is a second attempt to use this program +* scan + - load all plugins into array + - for each profile, scan all plugins. Remember duplicate matches. +* ask questions + - Questions for installers + - User file tree to copy +* Prepare HD: checkpoint, clean up, backup, defrag, repartition +* start linux VM: install virtualbox, extensions, download iso, automate install, install VM, launch +* Installs with progress + - apt-get update + upgrade + - Copy files + - Install packages + +Use cases +* Windows to dual-boot Ubuntu (default goal) +* Ubuntu VM install. Install Ubuntu into a VM. +* Ubuntu is already installed in a partition. Export Windows config. +* Ubuntu is on a remote machine. Export Windows config over ssh. + +Post-Install use cases +* Clean: Re-run clean, and restore pagefile, hiberfil.sys, etc. +* Sync: Sync changes from Windows to Ubuntu +* Hop: Change distro, reinstall apps. +* Revert: Remove Ubuntu and go back to original configuration. +* Commit: Delete C: partition, grow linux to fill its space. + + + +class PathMatchPlugin + is_match() + path:$PROGRAMFILE/git +class RegistryMatchPlugin + REG:... +class DisplayNameRegexMatchPlugin + match: 'NAME:^Greenshot' + HKLM/HKCU:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall + ignore if no UninstallString + +Plugin + # Estimated time in minutes to complete task + estimate(config) + # Does this plugin match this app profile? + is_match(profile) + # User files that should be copied. + user_files(profile) + # Workflow Phases + # Do any pre-install cleaning or backup. + preclean(profile) + before_questions(ui, profile) + # Ask any questions. Can modify profile as necessary. + gui(ui, profile) + # Run before any installs + pre_install(profile) + # Install this app profile + install(profile) + # Run after all installs + post_install(profile) + +computers/model/brand + name: + laptop: true + (files) + + +UI tabs + +Install - main ui +Script - currently running scripts and progress bar. + Past is white, current is yellow, future is gray. +Log - past script + output + buttons: save, files (brower temp files) + + +Steps + +[x] Backup +[x] Clean +[x] Defrag +[x] Repartition +[x] Install +[x] ... + +[MCüç[MCMMCûCÛMC + +Advice + +Best models for Linux +* Dell +* Lenovo +* IBM Thinkpad + +[Abort] [Back] {Continue] + +Backup + +You should do full backup before continuing. +Click Abort if you'd like to stop and do a backu. + +[Abort] [Back] {Continue] +[Backup Manager] + +Cleanup + +We recommend cleaning your hard drive to free up space for the install +and to temporarily get unmoveable files out of the way. + +[x] Disable swap file +[x] Disable hibernate file +[x] Remove restore points +[x] Remove dumps +[x] Clean temp +[x] Defragment drive + +Swap and hibernate will be reset to their original values after the install is complete. + +[Abort] [Back] [Continue] + +Preparation steps. + +* Cleaning... +* Checking prerequisites... + (64bit, win10, not on battery, not fast boot, enough free space on Windows after clean) + +[Abort] [Back] {Continue] + +We suggest you back up your system before you being. + +Would you like us to perform a backup for you? ( ) Yes ( ) No +Would you like us to removed unnecessary files? (*) Yes ( ) No +Would you like us to defragment your drive? (*) Yes ( ) No +Would you like us to create a new partition for Linux (*) Yes ( ) No + +[Abort] [Back] {Continue] + +Backup + +???? + + +[Abort] [Back] [Continue] + +Repartition + +C: partition size: 120GB + +$windows = Resize-Partition -size 70GB -disknumber 0 -partition 5 +$system = New-Partition -size 30GB -disknumber 0 -offset after-partition($windows) +$home = New-Partition -usemaximumsize -disknumber 0 -offset after-partition($system) + + +[Partition Table] +[Abort] [Back] [Continue] + +Distro choice + +(*) Mint Cinnamon +( ) Mint Xfce (make default if low mem,cpu) +( ) Ubuntu +( ) XUbuntu +( ) KUbuntu + +[Abort] [Back] [Continue] + +Configurations + +[ ] Wallpaper +[ ] Lock screen +[ ] Screen saver +[x] Wifi +[x] Mouse sensitivity +[ ] Sounds +[x] Keyboard +[x] +[ ] VPN + +[Abort] [Back] [Continue] + +Applications + +7 Zip [^] +Evolution[^] +Thunderbird + +[Abort] [Back] [Continue] + +Wine Applications. + +These applications are installed but have no Linux counterparts. They can be run with WINE. + +[ ] Photoshop + +[Abort] [Back] [Continue] + +Additional Applications + +[x] Laptop power management (detect if a laptop) +[x] Automatic security updates +[ ] SSH server +[ ] TeamViewer +[ ] Steam +[ ] Synaptec +[x] MS Fonts +[x] VLC Media Player +[ ] zram +[ ] topgrade + +[Abort] [Back] [Continue] + +These files user files will be copied to /home/$USER. + +Source: C:\Users\$USER Dest: /home/$USER Owner: $USER:$USER Mode: 644 + [ ] AppData + [x] Photos + [x] .ssh + [x] id_rsa + +Source: C:\git Dest: /home/$USER/git Owner: $USER:$USER Mode: 644 + +(when adding, any dirs, check Windows file ownership and try to mimic) + + +[Abort] [Back] [Continue] + +Unmatched Applications + +No match was found for these applications, but an application icon was found. Select which you would like to run inside of the Windows VM. + +[ ] Photoshop +[x] Microsoft Office + +[Abort] [Back] [Continue] + +Unmatched Applications + +No match was found nor was any desktop icon. No action will be taken to install these applications. + +C++ Runtime + +[Abort] [Back] [Continue] + +Size. +C: is using ____ GB with ____ GB of free space. +Linux is estimaged to require ___ GB of space. + +How much space do you want to allocate for Linux? ____ GB +Windows will retain ___ GB of free space. + +[x] Install Linux on newly from free space. + +[Manage Partitions] [Skip] +[Abort] [Back] [Continue] + +Linux will be installed on drive _0_ partition _6_. + +Any data on the partition will be lost. + +[Manage Partitions] +[Abort] [Back] [Continue] + +Disclaimer + +yada yada yada yada yada +Not liable +Won't move everything + +[Abort] [Back] [Agree] [Disagree] + +Click Continue to start install. + +[x] Reboot into Linux after successful install. + +[Abort] [Back] [Continue] + +Progress + +11:35:32 Creating restore point... complete. +11:35:32 Cleaning up... complete. +11:35:32 Backing up... complete. +11:35:32 Defragmenting... +11:35:32 Repartitioning... +11:35:32 Installing Libreoffice... complete. +11:35:32 Copying user files... + +[%%%%%%%%%%%%%%%............] +[%%%%.......................] +Estiamated completion time: 3:40pm + +Done! + +You may now reboot to your Linux system. + +[Abort] [Back] +[Exit] [Linux VM] [Reboot] + +Detect Secure Boot +https://www.iceflatline.com/2009/09/how-to-dual-boot-windows-7-and-linux-using-bcdedit/ + + + + +Version 0.1 +* Many assumptions: Win 10, single C:, virtualbox, dual boot, Mint cinnamon +* If no "linux" partition, create it with powershell and bcdedit +* Download and Install ISO to partition. +* Launch in VM and then force launch of installer. +* Bash script for installing windows apps and transfering data. + +Side idea: ultimate distro hopper +* Tiny linux distro boots +* Grub like menu to choose which distro +* Menu Option to add one. +* Common home partition. contains info on packages to install. +* Other options: manage partitions, create recovery usb, recover windows. + + + + +------ FIRST TRY TO INSTLAL LINUX +Full image backup using Clonezilla +Full backup of all partitions from within Windows and do a test restore. +Defrag and Repartition using Powershell. Shrink C: and create linux-system and linux-home partitions. +Install Linux in VirtualBox on the Linux partitions. Automate the whole thing with powershell and Ubuntu kickstart. +Use Windows boot manager instead of Grub2 for boot menu. +Boot to Ubuntu and replace Win boot manager with Grub2 (if possible) +And then wipe it all and install Void Linux as that's what I want to use. I might buy another cheap laptop for these experiments. + +On Linux, create VirtualBox VM image using WIndows' raw partition. + +Final testing: +Reboot to test all scenarios: Linux w/Windows VM, Windows w/Linux VM. +Restore back to beginning. + +You can first disable System Protection, System restore files, Fast startup, Hibernation mode, kernel memory dump, and page files as least temporarily. +https://www.disk-partition.com/articles/size-of-available-shrink-space-in-mb-0-4348.html + + +Install Linux from Windows? + +Looking for feedback. + +For fun, I'm going to experiment with installing dual-boot Linux on a Windows Laptop. I know it's generally considered not possible due to such a thing, but I'd like to at least try. Where do you think I'd have the biggest issues with this plan?: + +------ +Fix +Quick clean (not hiber,swap) +Questions (incl. password) +Clean +Defrag +Reboot and Continue (w/o user intervention) +Defrag +Questions +Repartition +Download io +Download/install VirtualBox +Create VM + Installing + App installation + grub +Reboot to Linux w/auto-login +Disable auto-login +Alarm and notice of completion + +---- RECENT + +Testing: +* ./install-tools +* use vagrant build of windows VMs +* install stuff into the VM +* include a very simple http server and modify hosts file +* use as a snapshot from there +* mapping to linux home dir +* script to tell vagrant to use snapshot + +0.0.1 - not reliable, but usable. ++NSIS installer ++check freespace. tell user they need to free up space. ++mbr2gpt + ISO partition ++download ISO ++reboot (to ubiquity) + +0.0.2 ++enable swap (if previously disabled) + clear space +/check freespace. disable swap and tell user to reboot and try again. + mbr2gpt + ISO partition + download ISO + reboot (to ubiquity) + +0.1.0 - MVP + enable swap (if previously disabled) + clear space ++ask user: disk space + check freespace. disable swap and tell user to reboot and try again. + mbr2gpt + ISO partition ++shrink C: ++generate preseed values for simple install. No auto-approve + download ISO + reboot (to ubiquity) + +0.1.1 + enable swap (if previously disabled) ++skip to partition step if this is 2nd run. + clear space. ++checkpoint. + ask user: disk space. + mbr2gpt + ISO partition ++shrink C: +/generate preseed values. Will auto-approve, reboot, delete ISO post-install + download ISO + reboot (to ubiquity) + +* Pull down list of mirrors from site +* Ping each with timeout. +* use random 4 for download. use aria2 for download +* separate fat32 partition: no other files. +* run in background +* resume as needed (reboots) + +TOP TODO: preseed +# https://help.ubuntu.com/lts/installation-guide/example-preseed.txt +d-i partman-auto/init_automatically_partition select biggest_free +d-i partman-auto/choose_recipe select atomic + +ps1 tempalte - https://gist.github.com/9to5IT/9620683 +template engine - $ExecutionContext.InvokeCommand.ExpandString((get-content "preseed.cfg.tpl")) + +clean +disable-swap +defrag +mbr2gpt +download-iso +iso part +mount-iso +install-grub +- grub files +- grub.cfg +- preseed.cfg +- bcdedit +umount-iso +repartition +enable-swap +cleanup +- delete iso +- delete iso part diff --git a/doc/junk/install-vm.ps1 b/doc/junk/install-vm.ps1 new file mode 100644 index 0000000..4fe89ef --- /dev/null +++ b/doc/junk/install-vm.ps1 @@ -0,0 +1,80 @@ +#TODO: params: partitions(1,6), iso + +$USER="${env:USERNAME}" +$name="Mint2" +$password="mike68" +$tzone='EST' +$country='US' +$hostname='hostname' +$rawdisk='\\.\PHYSICALDRIVE0' + +if ( $(VBoxManage list vms | findstr "$name") ) { + VBoxManage unregistervm "$name" --delete +} + +VBoxManage createvm -name "$name" ` + --ostype Ubuntu_64 ` + --register + +VBoxManage modifyvm "$name" ` + --cpus 1 ` + --memory 1024 ` + --vram 12 + +# TODO: determine efi part# +VBoxManage internalcommands createrawvmdk ` + -filename 'C:\linux\partitions.vmdk' ` + -rawdisk "$rawdisk" -partitions '1,6' + +#TODO: +# Convert as if -relative had been passed. +# sed -ri 's/FLAT "\\.\PHYSICALDRIVE[1,6]" [0-9]+$/ZERO/' C:\linux\partitions.vmdk +# sed -ri 's/FLAT "\\.\PHYSICALDRIVE([1-9]+)" [0-9]$/FLAT "\\.\Harddisk0Partition\1" 0/' C:\linux\partitions.vmdk +# unmapped lines will have ZERO$ instead of FLAT.*$ +# 1st line is without -relative +# 1st col is size/12. 1st line last col is relative to beginning /512. +#-RW 171911168 FLAT "\\.\PHYSICALDRIVE0" 65820672 +#+RW 171911168 FLAT "\\.\Harddisk0Partition6" 0 + +VBoxManage storagectl "$name" ` + --name 'SATA Controller' --add sata ` + --controller IntelAHCI + +VBoxManage storageattach "$name" ` + --storagectl 'SATA Controller' ` + --port 0 --device 0 --type hdd ` + --medium 'C:\linux\partitions.vmdk' + +VBoxManage storagectl "$name" ` + --name 'IDE Controller' --add ide + +VBoxManage storageattach "$name" ` + --storagectl 'IDE Controller' ` + --port 0 --device 0 --type dvddrive ` + --medium 'C:\linux\mintcin.iso' + +#TODO: VBoxManage modifyvm "$name" --ioapic on +VBoxManage modifyvm "$name" --boot1 dvd --boot2 disk --boot3 none --boot4 none + +exit 0 +VBoxManage startvm "$name" + +VBoxManage controlvm "$name" acpipowerbutton + +#TODO: unattended w/o harming efi + +# [--password-file=file] [--full-user-name=name] +# [--additions-iso=add-iso] [--validation-kit-iso=testing-iso] [--locale=ll_CC] +# [--country=CC] [--time-zone=tz] [--hostname=fqdn] [--package-selection-adjustment=keyword] [--dry-run] +# [--auxiliary-base-path=path] [--image-index=number] [--script-template=file] [--post-install-template=file] +# [--post-install-command=command] [--extra-install-kernel-parameters=params] [--language=lang] + +vboxmanage unattended install "$name" ` + --user "$USER" --password="$password" ` + --install-additions ` + --time-zone "$tzone" ` + --hostname "$hostname" ` + --country "$country" ` + --iso 'C:\linux\mintcin.iso' ` + --start-vm gui + diff --git a/doc/junk/repartition.ps1 b/doc/junk/repartition.ps1 new file mode 100644 index 0000000..d7e5da1 --- /dev/null +++ b/doc/junk/repartition.ps1 @@ -0,0 +1,96 @@ +$linux_system_size = 40GB +$linux_home_size = 40GB +$letter = $env:HOMEDRIVE[0] + +# TODO: Parameters. +# Separate routine for repart: split c +# Call separate routine for VM installations: +# install-vm c [-bootmenu:true] + +# TODO: logging functions: format-list *, append, timestamp + +Write-Host "Defragmenting disk..." +Optimize-Volume -DriveLetter $letter -ReTrim -Defrag -SlabConsolidate -TierOptimize -NormalPriority + +$efi = (ls function:[d-z]: -n | ?{ !(test-path $_) } | random) +#TODO: this line failed first time I ran it: +mountvol.exe "$efi" /s +Compress-Archive -Path "$efi" -DestinationPath "C:\linux\efi.zip" +mountvol.exe "$efi" /d + +Write-Host "Backing up..." +$efi = (ls function:[d-z]: -n | ?{ !(test-path $_) } | random) +#TODO: this line failed first time I ran it: +mountvol $efi /s +#TODO: ex.txt with BCD,BCD.LOG +xcopy e: c:\linux\efi /s /e /exclude:c:\linux\ex.txt +#TODO: Compress-Archive -Path "$efi" -DestinationPath "C:\linux\efi.zip" +#TODO: cp -r /e /c/linux/efi +mountvol $efi /d +bcdedit /export c:\linux\bcd.bak +#TODO: read MBR +Write-Host "INITIAL" | Out-File -FilePath c:\linux\out.log -Append +Get-ComputerInfo | Out-File -FilePath c:\linux\out.log -Append +bcdedit /enum | Out-File -FilePath c:\linux\out.log -Append +Get-Partition | Out-File -FilePath c:\linux\out.log -Append +Get-Volume | Out-File -FilePath c:\linux\out.log -Append +Get-Disk | Out-File -FilePath c:\linux\out.log -Append + +Write-Host "Repartioning disk..." +$linuxsize = $linux_system_size + $linux_home_size +$winsizemin = (get-partitionsupportedsize -driveleter $letter).sizemin +$winfree = (Get-Volume -driveletter $letter).SizeRemaining +$winpart = Get-Partition -DriveLetter $letter +$available = $winpart.size - $winsizemin +$disk = $winpart.disknumber + +$memstatus = "$([Math]::Floor($winfree / 1GB)) GB free, $([Math]::Floor($available / 1GB)) GB available." +if( $linuxsize -gt $winfree) { throw "Not enough room. $memstatus" } +if( $linuxsize -gt $available) { throw "Hidden files are in the way. Try to clean and reboot again. $memstatus" } + +$winpart | Resize-Partition -Size ( $winpart.size - $linuxsize ) +$winpart = Get-Partition -DriveLetter $letter +$linux_system = new-partition -disknumber $disk -offset ( $winpart.offset + $winpart.size ) -size $linux_system_size +$linux_home = new-partition -disknumber $disk -offset ( $linux_system.offset + $linux_system.size ) -usemaximumsize + +Write-Host "Repartition done. Start of install." + +Write-Host "Downloading ISO..." +mkdir C:\linux +$iso_url='http://mirrors.kernel.org/linuxmint/stable/19.2/linuxmint-19.2-cinnamon-64bit.iso' +#TODO: use BitsTransfer - set policy. Start earlier. +(New-Object System.Net.WebClient).DownloadFile($iso_url, "C:\linux\live.iso") + +Write-Host "Installing VirtualBox..." +Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1')) +choco install -y virtualbox + +Write-Host "Creating VM..." +$rawdisk=(get-wmiobject win32_diskdrive -filter "index=${disk}").deviceId +#TODO: don't assume EFI is partition 1. Find by GUID +VBoxManage internalcommands createrawvmdk -filename "C:\linux\rawparts.vmdk" -rawdisk "$rawdisk" -partitions 1,$linux_system.partitionnumber,$linux_home.partitionnumber +#TODO: create VM with VBoxManage. --firmware efi. volume names should match the final names, if possible. +#TODO: which video mode +#TODO: use VMBoxManage unattended + preseed.cfg + +# Write-Host "Adding to boot menu..." +$parttype = (get-disk -disknumber $disk).partitionstyle +#TODO: download or copy *.efi file to C:\linux +#TODO: use bcdedit commands to add menu item, set timeout value. +#install easybcd, easyuefi for experimentation +#bcdedit /enum firmware +#bcdedit /create /c "Linux Mint" /application ????? +#Returns a value for {ID} +#bcdedit /set {ID} device partition=c: +#bcdedit {ID} PATH \linux\shimx64.efi (or grup4bcd.img) +#bcdedit /displayorder {ID} /addlast +#bcdedit /set {bootmgr} path \EFI\ubuntu\shimx64.efi +#bcdedit /set {bootmgr} path C:\linux\shimx64.efi + +Write-Host "FINAL" | Out-File -FilePath c:\linux\out.log -Append +bcdedit /list | Out-File -FilePath c:\linux\out.log -Append +Get-Partition | Out-File -FilePath c:\linux\out.log -Append +Get-Volume | Out-File -FilePath c:\linux\out.log -Append + +Write-Host "Complete." + diff --git a/doc/junk/tunic2.ps1 b/doc/junk/tunic2.ps1 new file mode 100644 index 0000000..a22257f --- /dev/null +++ b/doc/junk/tunic2.ps1 @@ -0,0 +1,842 @@ +# Automated install of an ISO file + +if( $args[0] -eq 'noop') { exit } # for syntax checking + +$iso_url='http://mirrors.kernel.org/linuxmint/stable/19.2/linuxmint-19.2-cinnamon-64bit.iso' + +$letter = $env:HOMEDRIVE[0] +$root_dir="${letter}:" +$tunic_dir="${env:ALLUSERSPROFILE}\tunic" +$tunic_data="${tunic_dir}" +$iso = "${tunic_data}\linux.iso" + +$MIN_DISK_FB = 15 + +# Do very basic initialization +function init() { + mkdir "$tunic_dir" -force | out-null +} + +# Disable swap, hibernate, restore, error reports, dumps +function disableSwap() { + Write-Host "Disabling swap..." + # Turn off hibernation and fast start + powercfg.exe /h off + REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Power" /V HiberbootEnabled /T REG_DWORD /D 0 /F + # Disable swap + $computersys = Get-WmiObject Win32_ComputerSystem -EnableAllPrivileges + $computersys.AutomaticManagedPagefile = $False + $computersys.Put() + #TODO: failed: wmic pagefile delete + +#TODO: custom size + $pagefile = gwmi win32_pagefilesetting + $pagefile.delete() + + #$pagefile = Get-WmiObject -Query "Select * From Win32_PageFileSetting Where Name like '%pagefile.sys'" + #$pagefile.InitialSize = 0 + #$pagefile.MaximumSize = 0 + #$pagefile.Put() + #ALT: delete or move pagefile.sys + #wmic computersystem set AutomaticManagedPagefile=False + #wmic pagefileset where name="C:\pagefile.sys" delete + + #TODO: REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\CrashControl" /V CrashDumpEnabled /T REG_DWORD /D 0 /F + #TODO: REG ADD "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\Windows Error Reporting" /v Disabled /T REG_DWORD /D 1 /F + Disable-WindowsErrorReporting + Disable-ComputerRestore -Drive "C:\" + + Write-Host "Swap disabled." +} + +function enableSwap() { + Write-Host "Re-enabling Swap" + + Enable-ComputerRestore -Drive C: + Enable-WindowsErrorReporting + + # Enable Swap + wmic pagefileset create name="C:\\pagefile.sys" + wmic pagefileset where name="C:\\pagefile.sys" set InitialSize=2048,MaximumSize=2048 + wmic computersystem set AutomaticManagedPagefile=True + + # Enable Hibernate + REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Power" /V HiberbootEnabled /T REG_DWORD /D 1 /F + # TODO: see if hibernate is support and/or if it was on before. + powercfg.exe /h on +} + +function clean() { + # Turn off swap + Write-Host "Cleaning file system..." + + $letter = $env:HOMEDRIVE[0] + + # Cleanup + Cleanmgr /sagerun:16 + Get-ComputerRestorePoint | Delete-ComputerRestorePoint + fsutil usn deletejournal /d /n "${letter}:" + vssadmin delete shadows /all /quiet + Dism /Online /Cleanup-Image /StartComponentCleanup /ResetBase + Clear-WindowsDiagnosticData -Force + + #TODO: chkdsk "${letter}:" + + Write-Host "Clean done." +} + +function defrag() { + Write-Host "Defragmenting disk..." + powercfg.exe /h off + REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Power" /V HiberbootEnabled /T REG_DWORD /D 0 /F + Optimize-Volume -DriveLetter $letter -Defrag + #TODO: powercfg.exe /h on +} + +function backupEfi() { + param([string]$file) + #TODO: from repartition.ps1 +} + +# Returns true if Linux can be installed. +function checks() { + #[System.Environment]::Is64BitOperatingSystem -and ` + #[System.Environment]::OSVersion.version.major >= 10 -and ` + #[System.Environment]::Version.major >= 3 -and ` + #([Security.Principal.WindowsPrincipal] ` + # [Security.Principal.WindowsIdentity]::GetCurrent() ` + #).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -and ` + #(get-disk -number $partc.diskNumber).partitionStyle -eq 'MBR') + #TODO: doesn't work in VM: Confirm-SecureBootUEFI + # existence of all pwsh lib functions + # Bitlocker: + #$BLinfo = Get-Bitlockervolume + #if($blinfo.ProtectionStatus -eq 'On' -and $blinfo.EncryptionPercentage -eq '100'){ + # write-output "'$env:computername - '$($blinfo.MountPoint)' is encrypted" + #} +} + +function checkSpace() { + # enough space for windows. for linux. + # plus iso x2 +} + +function toEfi() { + $partc = get-partition -driveletter C + if( (get-disk -number $partc.diskNumber).partitionStyle -eq 'MBR' ) { + Write-host "Converting from MBR to GPT..." + #backupMbr + mbr2gpt /validate /allowfullos + mbr2gpt /convert /allowfullos + } +} + +function downloadIso() { + if ( -not (Test-Path "$iso") ) { + $ciso = 'Z:\Downloads\linuxmint-19.2-cinnamon-64bit.iso' + if ( Test-Path "$ciso" ) { + Write-host "Copying ISO..." + copy "$ciso" "$iso" + } else { + Write-host "Downloading ISO... (this takes a long time)" + try { + (New-Object System.Net.WebClient).DownloadFile($iso_url, "$iso") + #TODO: verify integrity + } catch { + Remove-Item "$iso" + Throw "Download failed" + } + } + } +} + +# Returns the Linux timezone converted from Windows. +function getLinuxTimeZone() { + + # Download and load list of timezones + + $url = 'https://raw.githubusercontent.com/unicode-org/cldr/master/common/supplemental/windowsZones.xml' + $file = "$env:TEMP\windowsZones.xml" + if( ! (Test-Path $file -ErrorAction SilentlyContinue) ) { + $web = (New-Object System.Net.WebClient) + $web.DownloadFile($url, $file) + } + [xml]$xml = Get-Content $file + $nodes = $xml.supplementalData.windowsZones.mapTimezones.childNodes + + # Get Windows timezone and country code. + + $wtz = (get-timezone).id + $territory = (New-Object System.Globalization.RegionInfo (Get-Culture).Name).TwoLetterISORegionName + + # Scan for Linux equivalent + + $ltz = ($nodes | where-object { $_.other -eq $wtz -and $_.territory -eq $territory } ).type + if( ! $ltz ) { + # Direct hit failed. Use the generic territory, 001. This is most common case. + $ltz = ($nodes | where-object { $_.other -eq $wtz -and $_.territory -eq '001' } ).type + } + if( ! $ltz ) { + # Any match by name. + $ltz = ($nodes | where-object { $_.other -eq $wtz } | select -first 1 ).type + } + if( ! $ltz ) { + $ltz = 'UTC' + } + + return $ltz +} + +function installGrub() { + Write-host "Installing Grub..." + + # TODO: allocate drive letter. try..finally + #$efi = (ls function:[d-z]: -n | ?{ !(test-path $_) } | random) + $efi = "S:" + if ( -not (Test-Path "$efi") ) { + mountvol $efi /s + } + + if ( -not (Test-Path "$efi\boot\grub") ) { + $usb = "$(( mount-diskimage -imagepath "$iso" | get-volume ).driveletter):" + # Grub + mkdir "${efi}\boot\grub" -force | out-null + #TODO: shimx64.efi (shim*.deb file). + copy "${usb}\boot\grub\x86_64-efi" "${efi}\boot\grub\." -recurse + copy "${usb}\EFI\BOOT\grubx64.efi" "${efi}\boot\grub\." + copy "files\grub.cfg" "${efi}\boot\grub\." + # Preseed + copy "files\preseed.cfg" "${tunic_dir}\." + # iso + #TODO: remove if iso loopback works + #Write-host "Copying ISO..." + copy "${usb}\*" "${root_dir}\." -recurse + + dismount-diskimage -imagepath "$iso" | out-null + } + + $osloader = (bcdedit /copy '{bootmgr}' /d ubuntu).replace('The entry was successfully copied to ','').replace('.','') + bcdedit /set "$osloader" device "partition=$efi" + if ( Test-Path "$efi\boot\grub\shimx64.efi" ) { + bcdedit /set "$osloader" path \boot\grub\shimx64.efi + } else { + bcdedit /set "$osloader" path \boot\grub\grubx64.efi + } + bcdedit /set "$osloader" description "Linux ISO" + bcdedit /deletevalue "$osloader" locale + bcdedit /deletevalue "$osloader" inherit + bcdedit /deletevalue "$osloader" default + bcdedit /deletevalue "$osloader" resumeobject + bcdedit /deletevalue "$osloader" displayorder + bcdedit /deletevalue "$osloader" toolsdisplayorder + bcdedit /deletevalue "$osloader" timeout + bcdedit /set '{fwbootmgr}' displayorder "$osloader" /addfirst + + mountvol $efi /d +} + +function getInfo() { + $c_part = (get-partition -driveletter $letter)[0] + $c_minsize = (get-partitionsupportedsize -driveletter $letter).sizeMin + @{ + disk = $c_part.diskNumber; + letter = $letter; + number = $c_part.partitionNumber; + size = $c_part.size; + free = (get-volume -driveletter $letter).sizeRemaining; + available = ($c_part.size - $c_minsize); + offset = $c_part.offset + } +} + +function createIsoPartition() { + param([int] $space) + + Write-Host 'Mounting ISO...' + + # Gather stats + $info = getInfo + $iso_size = ( get-childitem -path "$iso" ).length + $iso_offset = $info.offset + $info.size - $iso_size + + if( $info.available -lt $iso_size ) { + throw "Not enough space to create ISO partition" + } + + # Partitioning + $c_size = ( $info.size - $iso_size - $space ) + resize-partition ` + -diskNumber $info.disk ` + -partitionNumber $info.number ` + -size $c_size + + $iso_part = new-partition ` + -disknumber $info.disk ` + -assignDriveLetter ` + -offset $iso_offset -size $iso_size + + # Copy ISO + $iso_part | format-volume -fileSystem FAT32 + + #TODO: mount iso + $usb = "${iso_part.driveLetter}:" + + copy "$iso" "$usb" -recurse + + #TODO: umount + + $iso_part.partitionNumber +} + +# Because PS sucks, we need to make these global. + +Add-Type -AssemblyName System.Windows.Forms +[System.Windows.Forms.Application]::EnableVisualStyles() + +$main = New-Object system.Windows.Forms.TableLayoutPanel +$sizeLabel = New-Object system.Windows.Forms.Label +$TotalValue = New-Object system.Windows.Forms.Label +$usedValue = New-Object system.Windows.Forms.Label +$freeValue = New-Object system.Windows.Forms.Label +$availValue = New-Object system.Windows.Forms.Label +$LinuxSize = New-Object system.Windows.Forms.TextBox +$username = New-Object system.Windows.Forms.TextBox +$password = New-Object system.Windows.Forms.TextBox +$password2 = New-Object system.Windows.Forms.TextBox +$hostname = New-Object system.Windows.Forms.TextBox +$agreeBox = New-Object system.Windows.Forms.CheckBox +$installbutton = New-Object system.Windows.Forms.Button + +$progress = New-Object system.Windows.Forms.TableLayoutPanel +$defragStatus = New-Object system.Windows.Forms.Label +$partStatus = New-Object system.Windows.Forms.Label +$dlStatus = New-Object system.Windows.Forms.Label +$grubStatus = New-Object system.Windows.Forms.Label +$rebootStatus = New-Object system.Windows.Forms.Label + +function calcGui() { + $letter = $env:HOMEDRIVE[0] + $volume = (Get-Volume -driveletter $letter) + $partc = (get-partition -driveletter $letter) + $partnext = (get-partition -disknumber $partc.disknumber | where-object { $_.partitionNumber -eq ($partc.partition + 1)}) + if( !! $partnext ) { + $gap = 0 + } else { + $gap = $partnext.offset - ( $partc.offset + $partc.size ) + } + $total = [math]::round( $volume.size / 1GB ) + $free = [math]::round( ($volume.sizeremaining + $gap) / 1GB ) + $avail = [math]::floor( ( (get-partitionsupportedsize -driveletter "$letter").sizeMin + $gap ) / 1GB) + # Used by windows. (gap is not part of calculation) + $used = [math]::round( ( $volume.size - $volume.sizeRemaining ) / 1GB ) + + $sizeLabel.text = "${letter}: Drive" + + $totalValue.text = "$total GB" + $freeValue.text = "$free GB" + $usedValue.text = "$used GB" + $availValue.text = "$avail GB" + + if( ! $linuxSize.text ) { + $linuxSize.text = "$(( [math]::max( $MIN_DISK_GB, [math]::min( [math]::floor($total / 2) , $avail ) ) ))" + } +} + +# Returns desired size of windows partition +function getPreferredSize() { + $partc = (get-partition -driveletter $letter) + $partnext = (get-partition -disknumber $partc.disknumber | where-object { $_.partitionNumber -eq ($partc.partitionNumber + 1)}) + if( !! $partnext ) { + $gap = 0 + } else { + $gap = $partnext.offset - ( $partc.offset + $partc.size ) + } + + # size entered in GUI + $linuxSizeNum = [double]::parse( $linuxSize.text ) * 1GB + # partition gap is already available + $winShrink = [math]::max([double]0, $linuxSizeNum - $gap ) + + return $partc.size - $winShrink +} + +# Create the partition gap +function createLinuxSpace() { + $letter = $env:HOMEDRIVE[0] + $newPartSize = (getPreferredSize) + + resize-partition -driveletter $letter -size $newPartSize + + #$partc = (get-partition -driveletter $letter) + #new-partition -disknumber $partc.diskNumber -offset ( $partc.offset + $partc.size ) -usemaximumsize +} + +function checkFields() { + $main.enabled = $false + + if( $password.text.length -eq 0 ) { + [Void][System.Windows.Forms.Messagebox]::Show("Password required.") + $main.enabled = $true + [Void]$password.focus() + return $false + } + + if( $password.text -ne $password2.text ) { + [Void][System.Windows.Forms.Messagebox]::Show("Passwords don't match") + $main.enabled = $true + [Void]$password.focus() + return $false + } + + if( ! $agreeBox.checked ) { + [Void][System.Windows.Forms.Messagebox]::Show("You must agree to terms to continue.") + $main.enabled = $true + [Void]$agreeBox.focus() + return $false + } + + $linuxSizeNum = [double]::parse( $linuxSize.text ) * 1GB + if( $linuxSizeNum -lt $MIN_DISK_GB * 1GB ) { + [Void][System.Windows.Forms.Messagebox]::Show("Linux requires at least ${MIN_DISK_GB}GB") + $main.enabled = $true + [Void]$linuxSize.focus() + return $false + } + + $letter = $env:HOMEDRIVE[0] + $avail = (get-partitionsupportedsize -driveletter "$letter").sizeMin + if( $linuxSizeNum -gt $avail ) { + [Void][System.Windows.Forms.Messagebox]::Show("Not enough available space.") + $main.enabled = $true + [Void]$linuxSize.focus() + return $false + } + + $main.enabled = $true + return $true +} + +function gui() { + + $Form = New-Object system.Windows.Forms.Form + $Form.text = "Tunic Linux Mint Installer" + $Form.autosize = $true + + # Progress Panel + + $progress.autosize = $true + $progress.Dock = [System.Windows.Forms.DockStyle]::Fill + $progress.padding = 10 + $progress.columnCount = 1 + $progress.visible = $false + #TODO: progress fields + #TODO: use job to run in background. + #TODO: Stop button + + # Requirement Status Panel + + $StatusPanel = New-Object system.Windows.Forms.TableLayoutPanel + $StatusPanel.BackColor = "#e3d7ed" + $StatusPanel.autosize = $true + $StatusPanel.Dock = [System.Windows.Forms.DockStyle]::Fill + $StatusPanel.padding = 5 + $StatusPanel.columnCount = 2 + $row = 0 + + $defragLabel = New-Object system.Windows.Forms.Label + $defragLabel.text = "Defragment" + $defragLabel.AutoSize = $true + + $defragStatus.text = "To Do" + $defragStatus.AutoSize = $true + + $statusPanel.controls.add($defragLabel, 0, $row) + $statusPanel.controls.add($defragStatus, 1, $row) + $row++ + + $partLabel = New-Object system.Windows.Forms.Label + $partLabel.text = "Re-Partition" + $partLabel.AutoSize = $true + + $partStatus.text = "To Do" + $partStatus.AutoSize = $true + + $statusPanel.controls.add($partLabel, 0, $row) + $statusPanel.controls.add($partStatus, 1, $row) + $row++ + + $dlLabel = New-Object system.Windows.Forms.Label + $dlLabel.text = "Download" + $dlLabel.AutoSize = $true + + $dlStatus.text = "To Do" + $dlStatus.AutoSize = $true + + $statusPanel.controls.add($dlLabel, 0, $row) + $statusPanel.controls.add($dlStatus, 1, $row) + $row++ + + $grubLabel = New-Object system.Windows.Forms.Label + $grubLabel.text = "Install Grub" + $grubLabel.AutoSize = $true + + $grubStatus.text = "To Do" + $grubStatus.AutoSize = $true + + $statusPanel.controls.add($grubLabel, 0, $row) + $statusPanel.controls.add($grubStatus, 1, $row) + $row++ + + $rebootLabel = New-Object system.Windows.Forms.Label + $rebootLabel.text = "Reboot" + $rebootLabel.AutoSize = $true + + $rebootStatus.text = "To Do" + $rebootStatus.AutoSize = $true + + $statusPanel.controls.add($rebootLabel, 0, $row) + $statusPanel.controls.add($rebootStatus, 1, $row) + $row++ + + $progress.controls.add($statusPanel) + + #TODO: button panel - Abort + $progress.controls.add( (New-Object system.Windows.Forms.Label) ) + + $form.controls.add($progress) + + # Main Input Panel + + $main.autosize = $true + $main.Dock = [System.Windows.Forms.DockStyle]::Fill + $main.padding = 10 + $main.columnCount = 1 + + $sizeLabel.text = "C: Drive" + $sizeLabel.AutoSize = $true + + $main.controls.add($sizeLabel) + + $SizePanel = New-Object system.Windows.Forms.TableLayoutPanel + $SizePanel.BackColor = "#e3d7ed" + $sizePanel.autosize = $true + $sizePanel.Dock = [System.Windows.Forms.DockStyle]::Fill + $sizePanel.padding = 5 + $sizePanel.columnCount = 2 + $row = 0 + + $totalLabel = New-Object system.Windows.Forms.Label + $totalLabel.text = "Total Size" + $totalLabel.AutoSize = $true + + $TotalValue.text = "0 GB" + $TotalValue.AutoSize = $true + + $sizePanel.controls.add($totalLabel, 0, $row) + $sizePanel.controls.add($totalValue, 1, $row) + $row++ + + $UsedLabel = New-Object system.Windows.Forms.Label + $UsedLabel.text = "Used by Windows" + $UsedLabel.AutoSize = $true + + $usedValue.text = "0 GB" + $usedValue.AutoSize = $true + + $sizePanel.controls.add($UsedLabel, 0, $row) + $sizePanel.controls.add($UsedValue, 1, $row) + $row++ + + $FreeLabel = New-Object system.Windows.Forms.Label + $FreeLabel.text = "Free" + $FreeLabel.AutoSize = $true + + $freeValue.text = "0 GB" + $freeValue.AutoSize = $true + + $sizePanel.controls.add($freeLabel, 0, $row) + $sizePanel.controls.add($freeValue, 1, $row) + $row++ + + $availLabel = New-Object system.Windows.Forms.Label + $availLabel.text = "Available" + $availLabel.AutoSize = $true + + $availValue.text = "0 GB" + $availValue.AutoSize = $true + + $sizePanel.controls.add($availLabel, 0, $row) + $sizePanel.controls.add($availValue, 1, $row) + $row++ + + $LinuxLabel = New-Object system.Windows.Forms.Label + $LinuxLabel.text = "Linux Size" + $LinuxLabel.AutoSize = $true + + $LinuxSize.multiline = $false + $LinuxSize.AutoSize = $true + $LinuxSize.width = 30 + + $sizePanel.controls.add($linuxLabel, 0, $row) + $sizePanel.controls.add($linuxSize, 1, $row) + $row++ + + $main.controls.add($sizePanel) + + $cleanPanel = New-Object system.Windows.Forms.FlowLayoutPanel + $cleanPanel.padding = 5 + $cleanPanel.AutoSize = $true + + $cleanButton = New-Object system.Windows.Forms.Button + $cleanButton.text = "Clean" + $cleanButton.tabStop = $false + $cleanPanel.controls.add($cleanButton) + + $defragButton = New-Object system.Windows.Forms.Button + $defragButton.text = "Defrag" + $defragButton.tabStop = $false + $cleanPanel.controls.add($defragButton) + + $parterButton = New-Object system.Windows.Forms.Button + $parterButton.text = "Partitions" + $parterButton.tabStop = $false + $cleanPanel.controls.add($parterButton) + + $main.controls.add($cleanPanel) + + $idGroupLabel = New-Object system.Windows.Forms.Label + $idGroupLabel.text = "Identifcation" + $idGroupLabel.AutoSize = $true + + $main.controls.add($idGroupLabel) + + $idPanel = New-Object system.Windows.Forms.TableLayoutPanel + $idPanel.autosize = $true + $idPanel.BackColor = "#e3d7ed" + $idPanel.Dock = [System.Windows.Forms.DockStyle]::Fill + $idPanel.padding = 5 + $idPanel.columnCount = 2 + $row = 0 + + $usernameLabel = New-Object system.Windows.Forms.Label + $usernameLabel.text = "User Name" + $usernameLabel.AutoSize = $true + + $username.multiline = $false + $username.AutoSize = $true + $username.tabStop = $false + + $idPanel.controls.add($usernameLabel, 0, $row) + $idPanel.controls.add($username, 1, $row) + $row++ + + $passwordLabel = New-Object system.Windows.Forms.Label + $passwordLabel.text = "Password" + $passwordLabel.AutoSize = $true + + $password.passwordChar = '*' + $password.multiline = $false + $password.AutoSize = $true + + $idPanel.controls.add($passwordLabel, 0, $row) + $idPanel.controls.add($password, 1, $row) + $row++ + + $password2Label = New-Object system.Windows.Forms.Label + $password2Label.text = "Password, again" + $password2Label.AutoSize = $true + + $password2.passwordChar = '*' + $password2.multiline = $false + $password2.AutoSize = $true + + $idPanel.controls.add($password2Label, 0, $row) + $idPanel.controls.add($password2, 1, $row) + $row++ + + $hostnameLabel = New-Object system.Windows.Forms.Label + $hostnameLabel.text = "Computer Name" + $hostnameLabel.AutoSize = $true + + $hostname.multiline = $false + $hostname.AutoSize = $true + $hostname.tabStop = $false + + $idPanel.controls.add($hostnameLabel, 0, $row) + $idPanel.controls.add($hostname, 1, $row) + $row++ + + $main.controls.add($idPanel) + + $agreeBox.Dock = [System.Windows.Forms.DockStyle]::Fill + $agreeBox.text = + "I understand this software could cause data loss " + + "and is provided as-is without any warrantee. " + + "I shall not hold the authors liable for any damages whatsoever." + $agreeBox.AutoSize = $false + $agreeBox.height = 50 + + $main.controls.add($agreeBox) + + $buttonPanel = New-Object system.Windows.Forms.FlowLayoutPanel + $buttonPanel.padding = 5 + $buttonPanel.AutoSize = $true + + $abortButton = New-Object system.Windows.Forms.Button + $abortButton.text = "Abort" + $abortButton.tabStop = $false + $buttonPanel.controls.add($abortButton) + + $installbutton.text = "Continue" + $buttonPanel.controls.add($installButton) + + $main.controls.add($buttonPanel) + + $form.controls.add($main) + + # Default feild values + calcGui + + $username.text = [System.Environment]::UserName + $hostname.text = [System.Environment]::MachineName + + # Actions + + $cleanButton.add_click({ + $main.enabled = $false + try { + start-process cleanmgr -wait + calcGui + } finally { + $main.enabled = $true + } + }) + + $defragButton.add_click({ + $main.enabled = $false + try { + start-process dfrgui -wait + calcGui + } finally { + $main.enabled = $true + } + }) + + $parterButton.add_click({ + $main.enabled = $false + try { + start-process diskmgmt.msc -wait + calcGui + } finally { + $main.enabled = $true + } + }) + + $abortButton.add_click( { + $form.close() + }) + + $installButton.add_click({ + if( (checkFields) ) { + $main.visible = $false + $progress.visible = $true + #TODO: Run as PSJob, remove doevents + [System.Windows.Forms.Application]::DoEvents() + + init + + $defragStatus.text = 'In Progress' + [System.Windows.Forms.Application]::DoEvents() + defrag + $defragStatus.text = 'Done' + + $partStatus.text = 'In Progress' + [System.Windows.Forms.Application]::DoEvents() + createLinuxSpace + $partStatus.text = 'Done' + + $dlStatus.text = 'In Progress' + [System.Windows.Forms.Application]::DoEvents() + downloadIso + $dlStatus.text = 'Done' + + $grubStatus.text = 'In Progress' + [System.Windows.Forms.Application]::DoEvents() + installGrub + $grubStatus.text = 'Done' + + $rebootStatus.text = 'In Progress' + [System.Windows.Forms.Application]::DoEvents() + Restart-Computer + } + }) + + return $form +} + + +$op = $args[0] + +switch($op) { + {$_ -eq "install-prep" } { + # The user is watching, so let's get slow stuff out of the way first. + checks + init + clean + disableSwap + defrag + downloadIso + toEfi # Warn user to change fw. boot to fwsetup + #rebootAndContinue "install" + } + {$_ -eq "get-info" } { + #outputs json for use in NSIS + #out: letter, disk-type, parts(offset, current, free, available) + getInfo | convertTo-json + } + {$_ -eq "download-iso" } { + # Separated for testing purposes + downloadIso + } + {$_ -eq "install" } { + checks + checkSpace + init + #enableSwap + downloadIso # in case install-prep wasn't run + #backupEfi "..." + installGrub + #backupEfi "..." + #setSizes -windows 30GB -system 20GB -user 90GB -iso 2GB + #installIsoVolume -delete-file + Restart-Computer # boot into linux + } + {$_ -eq "restore-efi" } { + #restoreEfi $args[1] + } + {$_ -eq "disable-swap" } { + disableSwap +# Restart-Computer + } + {$_ -eq "defrag" } { + defrag + } + {$_ -eq "uninstall" } { + # remove linux, remove grub, remove iso vol + #Restart-Computer + } + {$_ -eq "gui2" } { + # TODO: remove. for testing purposes. + $form = (gui) + echo '---' + $form.show() + sleep 6 + $form.close() + } + default { + checks + $form = (gui) + $form.showDialog() + } +} + diff --git a/doc/junk/unclean.ps1 b/doc/junk/unclean.ps1 new file mode 100644 index 0000000..8deac3d --- /dev/null +++ b/doc/junk/unclean.ps1 @@ -0,0 +1,14 @@ +# Re-enable all things clean.ps1 disabled + +Enable-ComputerRestore -Drive C: +Enable-WindowsErrorReporting + +# Enable Swap +wmic pagefileset create name="C:\\pagefile.sys" +wmic pagefileset where name="C:\\pagefile.sys" set InitialSize=2048,MaximumSize=2048 +wmic computersystem set AutomaticManagedPagefile=True + +# Enable Hibernate +REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Power" /V HiberbootEnabled /T REG_DWORD /D 1 /F +powercfg.exe /h on + diff --git a/doc/tunic-logo.svg b/doc/tunic-logo.svg new file mode 100644 index 0000000..7ba97be --- /dev/null +++ b/doc/tunic-logo.svg @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/files/7z.conf b/files/7z.conf new file mode 100644 index 0000000..cb333ca --- /dev/null +++ b/files/7z.conf @@ -0,0 +1,6 @@ + ;!@Install@!UTF-8! +Title="Tunic Linux Installer" +ExecuteFile="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" +ExecuteParameters="-executionpolicy bypass -nologo -noninteractive -windowstyle hidden -file tunic.ps1" +Wait="yes" +;!@InstallEnd@! diff --git a/files/grub.cfg b/files/grub.cfg new file mode 100644 index 0000000..8a5dc2c --- /dev/null +++ b/files/grub.cfg @@ -0,0 +1,44 @@ +set ALLUSERSPROFILE='/ProgramData' +set tunic_dir="${ALLUSERSPROFILE}/tunic" +set iso_path="${tunic_dir}/linux.iso" + +set timeout=2 + +insmod part_gpt + +menuentry "Automatic Install" { + insmod ntfs + search --set=root --file $iso_path + loopback loop ($root)$iso_path + linux (loop)/casper/vmlinuz file=/isodevice${tunic_dir}/preseed.cfg automatic-ubiquity boot=casper iso-scan/filename=${iso_path} toram noprompt -- +# linux (loop)/casper/vmlinuz file=(loop)/preseed/linuxmint.seed preseed/file=($root)${tunic_dir}/preseed.cfg boot=casper iso-scan/filename=${iso_path} quiet -- +# linux /casper/vmlinuz file=(loop)/preseed/linuxmint.seed boot=casper xforcevesa iso-scan/filename=${iso_path} ramdisk_size=1048576 root=/dev/ram rw noapic noacpi nosplash irqpoll -- + initrd (loop)/casper/initrd.lz +} + +menuentry "Linux ISO - loopback" { + insmod ntfs + search --set=root --file $iso_path + loopback loop ($root)$iso_path + linux (loop)/casper/vmlinuz file=(loop)/preseed/linuxmint.seed boot=casper iso-scan/filename=${iso_path} -- + initrd (loop)/casper/initrd.lz +} + +menuentry "Linux ISO - ntfs" { + insmod ntfs + search --set=root --file $iso_path + linux /casper/vmlinuz file=/preseed/linuxmint.seed boot=casper iso-scan/filename=${iso_path} -- + initrd /casper/initrd.lz +} + +menuentry 'Windows Boot Manager' { + insmod fat + set loader=/EFI/Microsoft/Boot/bootmgfw.efi + search --set=root --file $loader + chainloader ($root)$loader +} + +menuentry 'Firmware Configuration' { + fwsetup +} + diff --git a/files/preseed.cfg b/files/preseed.cfg new file mode 100644 index 0000000..34699c7 --- /dev/null +++ b/files/preseed.cfg @@ -0,0 +1,46 @@ +# Partition + +d-i ubiquity/partman-skip-unmount boolean true +d-i partman/unmount_active boolean false +d-i partman/filter_mounted boolean false + +d-i partman-auto/disk string /dev/sda +d-i partman-auto/choose_recipe select atomic +d-i partman-auto/init_automatically_partition select biggest_free + +d-i partman-partitioning/confirm_write_new_label boolean true +d-i partman/choose_partition select finish +d-i partman/confirm boolean true +d-i partman/confirm_nooverwrite boolean true + +# Locale + +d-i debian-installer/locale string $( (get-culture).ietfLanguageTag.replace('-','_') ).UTF-8 +d-i debian-installer/language string $( (get-culture).TwoLetterISOLanguageName ) +d-i debian-installer/country string $( (New-Object System.Globalization.RegionInfo (Get-Culture).Name).TwoLetterISORegionName.toLower() ) +d-i time/zone string $( getLinuxTimezone ) + +# Keyboard + +d-i keyboard-configuration/xkb-keymap select us +d-i keyboard-configuration/layoutcode select us +d-i console-setup/ask_detect boolean false + +# User + +d-i passwd/user-fullname string $( $fullname.text ) +d-i passwd/username string $( $username.text ) +d-i passwd/user-password password $( $password.text ) +d-i passwd/user-password-again passwo$rd $( $password.text ) +d-i user-setup/allow-password-weak boolean true +d-i netcfg/get_hostname string $( $hostname.text ) + +# Packages + +d-i base-installer/install-recommends boolean false + +# Reboot + +d-i finish-install/reboot_in_progress note +d-i ubiquity/reboot boolean true + diff --git a/test/test-loop.sh b/test/test-loop.sh new file mode 100755 index 0000000..b990033 --- /dev/null +++ b/test/test-loop.sh @@ -0,0 +1,194 @@ +#!/bin/bash +usage() { cat >&2 < [] + +${docs} +USAGE +} +docs=""; use() { docs="${docs}${1}"$'\n'; } + +set -euo pipefail + +vm_url='https://az792536.vo.msecnd.net/vms/VMBuild_20190311/VirtualBox/MSEdge/MSEdge.Win10.VirtualBox.zip' +VMBASE="MSEdge - Win10" +VMPARENT="tunic-parent-test" +VM="tunic-test" +SNAPSHOT="init" +SSHPORT=5222 +#TODO: remove: SIZE=51200 +user=IEUser +password='Passw0rd!' + +# Echo commands as they run +se() {( + set -x + "$@" +)} + +vboxmanage() {( + set -x + VBoxManage -q "$@" +)} + +_vmexists() { + vm="${1:-${VM}}" + VBoxManage -q list vms | grep -sq "\"${vm}\"" +} +_vmrunning() { + vm="${1:-${VM}}" + VBoxManage -q list runningvms | grep -sq "\"${vm}\"" +} + +use 'install-tools Install packages required for testing on Ubuntu' +install-tools() { + sudo apt install -y virtualbox openssh-client +} + +use 'build-vm Create a Windows VM image' +build-vm() { + echo "This builds 2 VMs:" + echo " $VMBASE : The stock one from Microsoft" + echo " $VMPARENT : THe parent VM of testing" + echo "Both will have a snapshoed called $SNAPSHOT" + echo "When tests are run, a VM named $VM will be created" + echo "" + echo 'Building VM...' + + if ! _vmexists "$VMBASE"; then + echo 'Downloading and extracting VM...' + if [[ ! -f "${VMBASE}.ova" ]]; then + se curl -f -o msvbox.tmp.zip -L "$vm_url" + mv msvbox.zip.tmp msvbox.zip + se unzip msvbox.zip + rm msvbox.zip + fi + + # create new VirtualBox VM + vboxmanage import "${VMBASE}.ova" + #TODO: rm "${VMBASE}.ova" + fi + + # Delete if exists + if _vmexists "$VMPARENT"; then + vboxmanage unregistervm "$VMPARENT" --delete + vboxmanage snapshot "$VMBASE" delete "$SNAPSHOT" + fi + + # Create $VMPARENT template clone + vboxmanage snapshot "$VMBASE" take "$SNAPSHOT" + vboxmanage clonevm "$VMBASE" --name "$VMPARENT" --snapshot "$SNAPSHOT" \ + --options link --register + vboxmanage modifyvm "$VMPARENT" \ + --memory 4096 --cpus 2 \ + --clipboard bidirectional + vboxmanage modifyvm "$VMPARENT" --natpf1 "guestssh,tcp,,${SSHPORT},,22" + vboxmanage sharedfolder add "$VMPARENT" --name linux \ + -hostpath "$HOME" -automount + + # Change size + #TODO: remove: storage="$(vboxmanage showvminfo "$VMPARENT" --machinereadable | grep 'IDE Controller-0-0' | cut -d= -f2 | sed 's/"//g')" + #TODO: remove: vboxmanage modifymedium disk "$storage" --resize "$SIZE" + + # Run test-setup + vboxmanage startvm "$VMPARENT" --type gui + se sleep 10 + while ! VBoxManage guestcontrol "$VMPARENT" run \ + --username "$user" --password "$password" \ + 'C:\Windows\System32\cmd.exe' /c -- rem &>/dev/null; do + se sleep 5 + done + vboxmanage guestcontrol "$VMPARENT" copyto \ + --username "$user" --password "$password" \ + --target-directory "C:\Users\$user\Desktop" \ + test-setup.ps1 + vboxmanage guestcontrol "$VMPARENT" copyto \ + --username "$user" --password "$password" \ + --target-directory "C:\Users\$user\Desktop" \ + test-setup.bat + #TODO: run test-setup.ps1 as admin shortcut on desktop + + echo 'VM created. Now do these steps:' + echo ' From the desktop run as administrator test-setup.ps1' + echo -n ' Hit enter to continue: ' + read -r + + vboxmanage modifyvm "$VMPARENT" --firmware efi +} + +use "create-vm Creates the test VM '$VM'" +use " from VM '$VMPARENT' snapshot '$SNAPSHOT'" +create-vm() { + if ! _vmexists; then + vboxmanage snapshot "$VMPARENT" take "$SNAPSHOT" + vboxmanage clonevm "$VMPARENT" --name "$VM" --snapshot "$SNAPSHOT" --options link --register + fi +} + +use "delete-vm Deletes VM" +delete-vm() { + if _vmexists; then + vboxmanage unregistervm "$VM" --delete + vboxmanage snapshot "$VMPARENT" delete "$SNAPSHOT" + while _vmexists; do sleep 2; done + fi +} + +use "start-vm Starts the test VM" +start-vm() { + if ! _vmrunning; then + vboxmanage startvm "$VM" --type gui + while ! nc -z localhost "$SSHPORT"; do sleep 2; done + sleep 25 + fi + echo 'Started VM.' +} + +use "stop-vm Stop running VM" +stop-vm() { + if _vmrunning; then + vboxmanage controlvm "$VM" poweroff + while _vmrunning; do sleep 2; done + sleep 2 + fi +} + +use "shell Run a shell command in the VM" +shell() { + sshpass -p "$password" ssh "$user"@localhost -p "$SSHPORT" "$@" +} + +use "power-up Recycle VM and start shell" +power-up() { + power-down + create-vm + start-vm + shell "$@" +} + +use "power-down Stop and delete VM" +power-down() { + stop-vm + delete-vm +} + +mirror() { + docker run --name nginx \ + -d \ + -p 80:80 \ + -v "$HOME/Downloads:/usr/share/nginx/html/linuxmint/stable/19.2" \ + nginx:alpine +} + +use "install-iso A complete test" +install-iso() { + #shell 'Z: && cd src/tunic && powershell -executionpolicy bypass -command .\tunic.ps1' + power-up 'Z: && cd src/tunic && powershell -executionpolicy bypass -command .\tunic.ps1 install' +} + +main() { + [[ "$#" -gt 0 ]] || usage + "$@" || usage +} + +main "$@" + diff --git a/test/test-setup.bat b/test/test-setup.bat new file mode 100644 index 0000000..a4efe56 --- /dev/null +++ b/test/test-setup.bat @@ -0,0 +1,5 @@ +@echo off + +cd "%~dp0" + +powershell -executionpolicy bypass -nologo -noninteractive -file test-setup.ps1 -args %* diff --git a/test/test-setup.ps1 b/test/test-setup.ps1 new file mode 100644 index 0000000..46fc378 --- /dev/null +++ b/test/test-setup.ps1 @@ -0,0 +1,121 @@ +# Configure VM for testing purposes + +# Parts were copied from ./tunic.ps1 + + +If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) +{ + Write-Host 'Escalating' + # Relaunch as an elevated process: + Start-Process powershell.exe "-File",('"{0}"' -f $MyInvocation.MyCommand.Path) -Verb RunAs + exit +} + +Write-host "Started." +$iso_url='http://mirrors.kernel.org/linuxmint/stable/19.2/linuxmint-19.2-cinnamon-64bit.iso' + +$letter = $env:HOMEDRIVE[0] +$tunic_dir="${env:ALLUSERSPROFILE}\tunic" +$iso = "${tunic_dir}\linux.iso" +# This is for testing only, so s'ok +$user = 'IEUser' +$password='Passw0rd!' + +# Disable Auto Updates + +$WindowsUpdatePath = "HKLM:SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate" +$AutoUpdatePath = "HKLM:SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" + +Remove-Item -Path $WindowsUpdatePath -Recurse -errorAction ignore + +New-Item -Path $WindowsUpdatePath +New-Item -Path $AutoUpdatePath + +Set-ItemProperty -Path $AutoUpdatePath -Name NoAutoUpdate -Value 1 + +# Disable Defender + +New-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows Defender" -Name DisableAntiSpyware -Value 1 -PropertyType DWORD -Force +New-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows Defender\Spynet" -Name SpyNetReporting -Value 0 -Force +New-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows Defender\Spynet" -Name SubmitSamplesConsent -Value 2 -Force + +# Disable Telemetry + +Set-Service -Name DiagTrack -StartupType Disabled +Set-Service -Name dmwappushservice -StartupType Disabled +New-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\OneDrive" -Name DisableFileSyncNGSC -Value 1 -Force +Get-ScheduledTask -TaskPath "\Microsoft\Windows\Customer Experience Improvement Program\" | Disable-ScheduledTask +New-Item "%ProgramData%\Microsoft\Diagnosis\ETLLogs\AutoLogger\AutoLogger-Diagtrack-Listener.etl" -ItemType File -Force +New-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\OneDrive" -Name DisableFileSyncNGSC -Value 1 -Force +New-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\AdvertisingInfo" -Name Enabled -Value 0 -Force +New-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\AppHost\EnableWebContentEvaluation" -Name Enabled -Value 0 -Force +New-ItemProperty -Path "HKCU:\Control Panel\International\User Profile" -Name HttpAcceptLanguageOptOut -Value 1 -Force +New-ItemProperty -Path "HKCU:\Software\Microsoft\Siuf\Rules" -Name PeriodInNanoSeconds -Value 0 -Force +New-ItemProperty -Path "HKCU:\Software\Microsoft\Siuf\Rules" -Name NumberOfSIUFInPeriod -Value 0 -Force +New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\WcmSvc\wifinetworkmanager\config" -Name AutoConnectAllowedOEM -Value 0 -Force +New-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\MRT" -Name DontReportInfectionInformation -Value 1 -Force +New-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\DataCollection" -Name AllowTelemetry -Value 0 -Force + +# Disable Cortana + +$path = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\Windows Search" +IF(!(Test-Path -Path $path)) { + New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows" -Name "Windows Search" +} +Set-ItemProperty -Path $path -Name "AllowCortana" -Value 1 +New-NetFirewallRule -DisplayName "Block Cortana Web Access" -Direction Outbound -Program "%windir%\systemapps\Microsoft.Windows.Cortana_cw5n1h2txyewy\SearchUI.exe" -Action Block + +# Auto Login + +$loginPath = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' +#TODO: next line said alread exists +New-ItemProperty -Path "$loginPath" -Name AutoAdminLogon -Value 1 -force +New-ItemProperty -Path "$loginPath" -Name DefaultUserName -Value "$user" -force +New-ItemProperty -Path "$loginPath" -Name DefaultPassword -Value "$password" -force + +# DNS + +#TODO: $gateway = (Get-NetIPConfiguration).ipv4defaultgateway.nexthop +#TODO: add-content 'C:\Windows\System32\drivers\etc\hosts' "$gateway mirrors.kernel.org" + +# Desktop Icons + +copy "C:\Users\$user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell\Windows PowerShell.lnk" ~/Desktop/. + +# Stay Awake + +$personalPath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\Personalization" +New-Item -Path "$personalPath" -errorAction ignore +New-ItemProperty -Path "$personalPath" -Name NoLockScreen -Value 1 -force + +powercfg /change monitor-timeout-ac 0 +powercfg /change disk-timeout-ac 0 +powercfg /change standby-timeout-ac 0 +powercfg /change hibernate-timeout-ac 0 + +# SSH + +Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0 +Start-Service sshd +Set-Service -Name sshd -StartupType 'Automatic' +#TODO: Get-NetFirewallRule -Name *ssh* +New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -PropertyType String -Force +New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShellCommandOption -Value "/c" -PropertyType String -Force +New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22 -errorAction ignore + +# Chocolatey installs + +install-packageprovider -name NuGet -force +$web = (New-Object System.Net.WebClient) +iex $web.DownloadString('https://chocolatey.org/install.ps1') + +choco install -y 7zip defraggler + +# Convert to EFI + +mbr2gpt /validate /allowfullos +mbr2gpt /convert /allowfullos + +Write-Host 'Done.' + +Stop-Computer -force diff --git a/tunic.ps1 b/tunic.ps1 new file mode 100644 index 0000000..5f334bf --- /dev/null +++ b/tunic.ps1 @@ -0,0 +1,786 @@ +# Automated install of an ISO file + +if( $args[0] -eq 'noop') { exit } # for syntax checking + +$global:iso_url='http://mirrors.kernel.org/linuxmint/stable/19.2/linuxmint-19.2-cinnamon-64bit.iso' +$global:shim_url = 'https://github.com/pop-os/iso/blob/master/data/efi/shimx64.efi.signed?raw=true' + +$global:letter = $env:HOMEDRIVE[0] +$global:root_dir="${letter}:" +$global:tunic_dir="${env:ALLUSERSPROFILE}\tunic" +$global:tunic_data="${tunic_dir}" +$global:iso = "${tunic_data}\linux.iso" + +$global:MIN_DISK_FB = 15 + + +# Do very basic initialization +if ( -not (Test-Path "$global:tunic_dir") ) { + mkdir "$global:tunic_dir" | out-null +} + +# Disable swap, hibernate, restore, error reports, dumps +function disableSwap() { + Write-Host "Disabling swap..." + + # Turn off hibernation and fast start + powercfg.exe /h off + REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Power" /V HiberbootEnabled /T REG_DWORD /D 0 /F + + # Disable swap + $computersys = Get-WmiObject Win32_ComputerSystem -EnableAllPrivileges + $computersys.AutomaticManagedPagefile = $False + $computersys.Put() + + $pagefile = Get-WmiObject win32_pagefilesetting + $pagefile.delete() + + Disable-WindowsErrorReporting + Disable-ComputerRestore -Drive "${global:root_dir}" + + Write-Host "Swap disabled." +} + +function enableSwap() { + Write-Host "Re-enabling Swap" + + Enable-ComputerRestore -Drive C: + Enable-WindowsErrorReporting + + # Enable Swap + wmic pagefileset create name="C:\\pagefile.sys" + wmic pagefileset where name="C:\\pagefile.sys" set InitialSize=2048,MaximumSize=2048 + wmic computersystem set AutomaticManagedPagefile=True + + # Enable Hibernate (but not fast start) + # TODO: see if hibernate is support and/or if it was on before. + powercfg.exe /h on +} + +function defrag() { + powercfg.exe /h off + REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Power" /V HiberbootEnabled /T REG_DWORD /D 0 /F + Optimize-Volume -DriveLetter $global:letter -Defrag + #TODO: powercfg.exe /h on - if was on before +} + +function die($msg) { + write-host $msg + [System.Windows.Forms.Messagebox]::Show($msg) + exit 1 +} + +function yes($q) { + $buttons = [System.Windows.Forms.MessageBoxButtons]::OKCancel + return [System.Windows.Forms.MessageBox]::Show("Message Text","Title", $buttons ) +} + +function openUrl($url) { + [System.Diagnostics.Process]::Start($url) +} + +# Returns true if Linux can be installed. +function checks() { + if( !([Security.Principal.WindowsPrincipal] ` + [Security.Principal.WindowsIdentity]::GetCurrent() ` + ).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) ) { + die( 'Must be an Administrator to run tunic' ) + } + + if( ! [System.Environment]::Is64BitOperatingSystem ) { + die( 'Only 64 bit systems supported' ) + } + + if( ! [System.Environment]::OSVersion.version.major -ge 10 ) { + die( 'Only Windows 10 supported' ) + } + + if( [System.Environment]::Version.major -lt 3 ) { + die( 'Powershell 3 or above required' ) + } + + $partc = ( get-partition -driveLetter $global:letter ) + if( (get-disk -number $partc.diskNumber).partitionStyle -eq 'MBR' ) { + if( yes('UEFI required. Would you like to read how to convert form MBR to EFI') ) { + openUrl('https://www.windowscentral.com/how-convert-mbr-disk-gpt-move-bios-uefi-windows-10') + } + exit 1 + } + + $blInfo = Get-Bitlockervolume + if( $blInfo.ProtectionStatus -eq 'On' ) { + die( 'Bitlocker encrypted drive not supported.' ) + } +} + +function downloadIso() { + if ( -not (Test-Path "$global:iso") ) { + $ciso = 'Z:\Downloads\linuxmint-19.2-cinnamon-64bit.iso' + if ( Test-Path "$ciso" ) { + copy "$ciso" "$global:iso" + } else { + try { + (New-Object System.Net.WebClient).DownloadFile($global:iso_url, "$global:iso") + #TODO: save to temp and move after. + #TODO: verify integrity + } catch { + Remove-Item "$global:iso" + Throw "Download failed" + } + } + } +} + +# Returns the Linux timezone converted from Windows. +function getLinuxTimeZone() { + # Download and load list of timezones + + $url = 'https://raw.githubusercontent.com/unicode-org/cldr/master/common/supplemental/windowsZones.xml' + $file = "$env:TEMP\windowsZones.xml" + if( ! (Test-Path $file -ErrorAction SilentlyContinue) ) { + $web = (New-Object System.Net.WebClient) + $web.DownloadFile($url, $file) + } + [xml]$xml = Get-Content $file + $nodes = $xml.supplementalData.windowsZones.mapTimezones.childNodes + + # Get Windows timezone and country code. + + $wtz = (get-timezone) + $tzName = $wtz.id + $territory = (New-Object System.Globalization.RegionInfo (Get-Culture).Name).TwoLetterISORegionName + + $zones = ($nodes | where-object { $_.other -eq $tzName } ) + if( $zones.count -eq 1 ) { + $ltz = $zones[0].type + } elseif( $zones.count -gt 1 ) { + + # Scan for exact Linux equivalent + $ltz = ($zones | where-object { $_.territory -eq $territory } ).type + if( ! $ltz ) { + # Direct hit failed. Use the generic territory. This is most common case. + $ltz = ($zones | where-object { $_.territory -eq '001' } ).type + } + + # Sloppy match + $ltz = $zones[0].type + } + else { + # Match by GMT and hour difference. + $offset = - $wtz.baseUtcOffset.totalHours + if( $offset -eq [math]::floor($offset) -and ` + -12 -le $offset -and $offset -le 12 -and ` + $offset -ne 0 ) { + + if( $offset -gt 0 ) { + $ltz = "Etc/GMT-${offset}" + } else { + $ltz = "Etc/GMT+${offset}" + } + } + else { + # We give up. This should never happen. + $ltz = "UTC" + } + } + + return $ltz +} + +function expandTemplate($filename) { + $str = ( get-content -path "$filename" ) + $str = $str.split("`n") -join "``n" + return $ExecutionContext.InvokeCommand.ExpandString( $str ) +} + +function installGrub() { + # TODO: allocate drive letter. try..finally + #$efi = (ls function:[d-z]: -n | ?{ !(test-path $_) } | random) + $efi = "S:" + if ( -not (Test-Path "$efi") ) { + mountvol $efi /s + } + + if ( -not (Test-Path "$efi\boot\grub") ) { + $usb = "$(( mount-diskimage -imagepath "$iso" | get-volume ).driveletter):" + # Grub + mkdir "${efi}\boot\grub" -force | out-null + copy "${usb}\boot\grub\x86_64-efi" "${efi}\boot\grub\." -recurse + copy "${usb}\EFI\BOOT\grubx64.efi" "${efi}\boot\grub\." + #TODO: use grubx64 if secureboot is not enabled + (New-Object System.Net.WebClient).DownloadFile($shim_url, "${efi}\boot\grub\shimx64.efi") + copy "files\grub.cfg" "${efi}\boot\grub\." + # Preseed + set-content -value (expandTemplate "files\preseed.cfg") -path "${global:tunic_dir}\preseed.cfg" + + dismount-diskimage -imagepath "$global:iso" | out-null + } + + if ( -not (Test-Path "${global:tunic_dir}\bcd-before.bak" ) ) { + bcdedit /export "${global:tunic_dir}\bcd-before.bak" + } + + #TODO: idempotent + $osloader = (bcdedit /copy '{bootmgr}' /d ubuntu).replace('The entry was successfully copied to ','').replace('.','') + bcdedit /set "$osloader" device "partition=$efi" + bcdedit /set "$osloader" path \boot\grub\shimx64.efi + bcdedit /set "$osloader" description "Linux ISO" + bcdedit /deletevalue "$osloader" locale + bcdedit /deletevalue "$osloader" inherit + bcdedit /deletevalue "$osloader" default + bcdedit /deletevalue "$osloader" resumeobject + bcdedit /deletevalue "$osloader" displayorder + bcdedit /deletevalue "$osloader" toolsdisplayorder + bcdedit /deletevalue "$osloader" timeout + bcdedit /set '{fwbootmgr}' displayorder "$osloader" /addfirst + + mountvol $efi /d + + bcdedit /export "${global:tunic_dir}\bcd-grub.bak" +} + +# Calculates globals gap and maxAvailable +function calcPartition() { + $letter = $global:letter + $global:partc = (get-partition -driveletter $letter) + $disk = (get-disk -number $global:partc.diskNumber) + + # Calculate Gap + $partnext = (get-partition -disknumber $global:partc.disknumber | where-object { $_.partitionNumber -eq ($global:partc.partitionNumber + 1)}) + if( ! $partnext ) { + #TODO: figure out hey -1MB needed + $global:gap = $disk.size - ( $global:partc.offset + $global:partc.size ) - 1MB + } else { + $global:gap = $partnext.offset - ( $global:partc.offset + $global:partc.size ) + } + + # Calculate available + $global:maxAvailable = $global:partc.size - (get-partitionsupportedsize -driveletter "$letter").sizeMin + $global:gap + + #TODO: remove + write-host "$($partc.partitionNumber) partc.offset,size $($partc.offset / 1GB),$($partc.size / 1GB) next.offset $($partnext.offset / 1GB) disk.size $($disk.size / 1GB) gap $($global:gap / 1GB) avail $($global:maxAvailable / 1GB)" + write-host "$($partc.partitionNumber) partc.offset,size $($partc.offset),$($partc.size) next.offset $($partnext.offset) disk.size $($disk.size) gap $($global:gap) avail $($global:maxAvailable)" +} + +function repartition() { + $letter = $global:letter + $global:partc = (get-partition -driveletter $letter) + + # size entered in GUI + $linuxSizeNum = [double]::parse( $global:linuxSize.text ) * 1GB + + $shrinkBy = $linuxSizeNum - $global:gap + + $newSize = $global:partc.size - ( $shrinkBy ) + + #TODO: remove + write-host "lsize $linuxSizeNum partc.size $( $global:partc.size ) shrinkBy $shrinkBy size $newSize" + + if( $shrinkBy -gt 0 ) { + resize-partition -driveletter $letter -size $newSize + } +} + +function calcGui() { + calcPartition + + $letter = $global:letter + $volume = (Get-Volume -driveletter $letter) + + $total = [math]::round( $volume.size / 1GB ) + $free = [math]::round( $volume.sizeremaining / 1GB ) + $used = [math]::round( ( $volume.size - $volume.sizeRemaining ) / 1GB ) + $avail = [math]::floor( $global:maxAvailable / 1GB ) + + $global:sizeLabel.text = "${letter}: Drive" + + $global:totalValue.text = "$total GB" + $global:freeValue.text = "$free GB" + $global:usedValue.text = "$used GB" + $global:availValue.text = "$avail GB" + + if( ! $global:linuxSize.text ) { + $global:linuxSize.text = "$(( [math]::max( $global:MIN_DISK_GB, [math]::min( [math]::floor($total / 2) , $avail ) ) ))" + } +} + +function initFields() { + checks + calcGui + + $userInfo = ( Get-WMIObject Win32_UserAccount | where caption -eq (whoami) ) + $fullname.text = $userInfo.fullName + $username.text = $userInfo.name.toLower() + $hostname.text = $userInfo.psComputerName +} + +function checkFields() { + $global:main.enabled = $false + + if( $password.text.length -eq 0 ) { + [Void][System.Windows.Forms.Messagebox]::Show("Password required.") + $global:main.enabled = $true + [Void]$global:password.focus() + return $false + } + + if( $global:password.text -ne $global:password2.text ) { + [Void][System.Windows.Forms.Messagebox]::Show("Passwords don't match") + $global:main.enabled = $true + [Void]$global:password.focus() + return $false + } + + if( ! $global:agreeBox.checked ) { + [Void][System.Windows.Forms.Messagebox]::Show("You must agree to terms to continue.") + $global:main.enabled = $true + [Void]$global:agreeBox.focus() + return $false + } + + $linuxSizeNum = [double]::parse( $global:linuxSize.text ) * 1GB + if( $linuxSizeNum -lt $global:MIN_DISK_GB * 1GB ) { + [Void][System.Windows.Forms.Messagebox]::Show("Linux requires at least ${MIN_DISK_GB}GB") + $global:main.enabled = $true + [Void]$global:linuxSize.focus() + return $false + } + + if( $linuxSizeNum -gt $global:maxAvailable ) { + [Void][System.Windows.Forms.Messagebox]::Show("Not enough available space.") + $global:main.enabled = $true + [Void]$global:linuxSize.focus() + return $false + } + + $global:main.enabled = $true + return $true +} + +function gui() { + + Add-Type -AssemblyName System.Windows.Forms + [System.Windows.Forms.Application]::EnableVisualStyles() + + $Form = New-Object system.Windows.Forms.Form + $Form.text = "Tunic Linux Mint Installer" + $Form.autosize = $true + + # Main Input Panel + $global:main = New-Object system.Windows.Forms.TableLayoutPanel + $main.autosize = $true + $main.Dock = [System.Windows.Forms.DockStyle]::Fill + $main.padding = 10 + $main.columnCount = 1 + + $global:sizeLabel = New-Object system.Windows.Forms.Label + $sizeLabel.text = "C: Drive" + $sizeLabel.AutoSize = $true + + $main.controls.add($sizeLabel) + + $SizePanel = New-Object system.Windows.Forms.TableLayoutPanel + $SizePanel.BackColor = "#e3d7ed" + $sizePanel.autosize = $true + $sizePanel.Dock = [System.Windows.Forms.DockStyle]::Fill + $sizePanel.padding = 5 + $sizePanel.columnCount = 2 + $row = 0 + + $totalLabel = New-Object system.Windows.Forms.Label + $totalLabel.text = "Total Size" + $totalLabel.AutoSize = $true + + $global:TotalValue = New-Object system.Windows.Forms.Label + $TotalValue.text = "0 GB" + $TotalValue.AutoSize = $true + + $sizePanel.controls.add($totalLabel, 0, $row) + $sizePanel.controls.add($totalValue, 1, $row) + $row++ + + $UsedLabel = New-Object system.Windows.Forms.Label + $UsedLabel.text = "Used by Windows" + $UsedLabel.AutoSize = $true + + $global:usedValue = New-Object system.Windows.Forms.Label + $usedValue.text = "0 GB" + $usedValue.AutoSize = $true + + $sizePanel.controls.add($UsedLabel, 0, $row) + $sizePanel.controls.add($UsedValue, 1, $row) + $row++ + + $FreeLabel = New-Object system.Windows.Forms.Label + $FreeLabel.text = "Free" + $FreeLabel.AutoSize = $true + + $global:freeValue = New-Object system.Windows.Forms.Label + $freeValue.text = "0 GB" + $freeValue.AutoSize = $true + + $sizePanel.controls.add($freeLabel, 0, $row) + $sizePanel.controls.add($freeValue, 1, $row) + $row++ + + $availLabel = New-Object system.Windows.Forms.Label + $availLabel.text = "Available" + $availLabel.AutoSize = $true + + $global:availValue = New-Object system.Windows.Forms.Label + $availValue.text = "0 GB" + $availValue.AutoSize = $true + + $sizePanel.controls.add($availLabel, 0, $row) + $sizePanel.controls.add($availValue, 1, $row) + $row++ + + $LinuxLabel = New-Object system.Windows.Forms.Label + $LinuxLabel.text = "Linux Size" + $LinuxLabel.AutoSize = $true + + $global:LinuxSize = New-Object system.Windows.Forms.TextBox + $LinuxSize.multiline = $false + $LinuxSize.AutoSize = $true + $LinuxSize.width = 30 + + $sizePanel.controls.add($linuxLabel, 0, $row) + $sizePanel.controls.add($linuxSize, 1, $row) + $row++ + + $main.controls.add($sizePanel) + + $cleanPanel = New-Object system.Windows.Forms.FlowLayoutPanel + $cleanPanel.padding = 5 + $cleanPanel.AutoSize = $true + + $cleanButton = New-Object system.Windows.Forms.Button + $cleanButton.text = "Clean" + $cleanButton.tabStop = $false + $cleanPanel.controls.add($cleanButton) + + $defragButton = New-Object system.Windows.Forms.Button + $defragButton.text = "Defrag" + $defragButton.tabStop = $false + $cleanPanel.controls.add($defragButton) + + $parterButton = New-Object system.Windows.Forms.Button + $parterButton.text = "Partitions" + $parterButton.tabStop = $false + $cleanPanel.controls.add($parterButton) + + $main.controls.add($cleanPanel) + + $idGroupLabel = New-Object system.Windows.Forms.Label + $idGroupLabel.text = "Identifcation" + $idGroupLabel.AutoSize = $true + + $main.controls.add($idGroupLabel) + + $idPanel = New-Object system.Windows.Forms.TableLayoutPanel + $idPanel.autosize = $true + $idPanel.BackColor = "#e3d7ed" + $idPanel.Dock = [System.Windows.Forms.DockStyle]::Fill + $idPanel.padding = 5 + $idPanel.columnCount = 2 + $row = 0 + + $usernameLabel = New-Object system.Windows.Forms.Label + $usernameLabel.text = "User Name" + $usernameLabel.AutoSize = $true + + $global:username = New-Object system.Windows.Forms.TextBox + $username.multiline = $false + $username.AutoSize = $true + $username.tabStop = $false + + $idPanel.controls.add($usernameLabel, 0, $row) + $idPanel.controls.add($username, 1, $row) + $row++ + + $passwordLabel = New-Object system.Windows.Forms.Label + $passwordLabel.text = "Password" + $passwordLabel.AutoSize = $true + + $global:password = New-Object system.Windows.Forms.TextBox + $password.passwordChar = '*' + $password.multiline = $false + $password.AutoSize = $true + + $idPanel.controls.add($passwordLabel, 0, $row) + $idPanel.controls.add($password, 1, $row) + $row++ + + $password2Label = New-Object system.Windows.Forms.Label + $password2Label.text = "Password, again" + $password2Label.AutoSize = $true + + $global:password2 = New-Object system.Windows.Forms.TextBox + $password2.passwordChar = '*' + $password2.multiline = $false + $password2.AutoSize = $true + + $idPanel.controls.add($password2Label, 0, $row) + $idPanel.controls.add($password2, 1, $row) + $row++ + + $fullNameLabel = New-Object system.Windows.Forms.Label + $fullNameLabel.text = "Full Name" + $fullNameLabel.AutoSize = $true + + $global:fullName = New-Object system.Windows.Forms.TextBox + $fullName.multiline = $false + $fullName.AutoSize = $true + $fullName.tabStop = $false + + $idPanel.controls.add($fullNameLabel, 0, $row) + $idPanel.controls.add($fullName, 1, $row) + $row++ + + $hostnameLabel = New-Object system.Windows.Forms.Label + $hostnameLabel.text = "Computer Name" + $hostnameLabel.AutoSize = $true + + $global:hostname = New-Object system.Windows.Forms.TextBox + $hostname.multiline = $false + $hostname.AutoSize = $true + $hostname.tabStop = $false + + $idPanel.controls.add($hostnameLabel, 0, $row) + $idPanel.controls.add($hostname, 1, $row) + $row++ + + $main.controls.add($idPanel) + + $global:agreeBox = New-Object system.Windows.Forms.CheckBox + $agreeBox.Dock = [System.Windows.Forms.DockStyle]::Fill + $agreeBox.text = + "I understand this software could cause data loss " + + "and is provided as-is without any warrantee. " + + "I shall not hold the authors liable for any damages whatsoever." + $agreeBox.AutoSize = $false + $agreeBox.height = 50 + + $main.controls.add($agreeBox) + + $buttonPanel = New-Object system.Windows.Forms.FlowLayoutPanel + $buttonPanel.padding = 5 + $buttonPanel.AutoSize = $true + + $abortButton = New-Object system.Windows.Forms.Button + $abortButton.text = "Abort" + $abortButton.tabStop = $false + $buttonPanel.controls.add($abortButton) + + $global:installbutton = New-Object system.Windows.Forms.Button + $installbutton.text = "Continue" + $buttonPanel.controls.add($installButton) + + $main.controls.add($buttonPanel) + + $form.controls.add($main) + + # Progress Panel + + $global:progress = New-Object system.Windows.Forms.TableLayoutPanel + $progress.autosize = $true + $progress.Dock = [System.Windows.Forms.DockStyle]::Fill + $progress.padding = 10 + $progress.columnCount = 1 + $progress.visible = $false + #TODO: progress fields + #TODO: use job to run in background. + #TODO: Stop button + + # Requirement Status Panel + + $StatusPanel = New-Object system.Windows.Forms.TableLayoutPanel + $StatusPanel.BackColor = "#e3d7ed" + $StatusPanel.autosize = $true + $StatusPanel.Dock = [System.Windows.Forms.DockStyle]::Fill + $StatusPanel.padding = 5 + $StatusPanel.columnCount = 2 + $row = 0 + + $defragLabel = New-Object system.Windows.Forms.Label + $defragLabel.text = "Defragment" + $defragLabel.AutoSize = $true + + $global:defragStatus = New-Object system.Windows.Forms.Label + $defragStatus.text = "To Do" + $defragStatus.AutoSize = $true + + $statusPanel.controls.add($defragLabel, 0, $row) + $statusPanel.controls.add($defragStatus, 1, $row) + $row++ + + $partLabel = New-Object system.Windows.Forms.Label + $partLabel.text = "Re-Partition" + $partLabel.AutoSize = $true + + $global:partStatus = New-Object system.Windows.Forms.Label + $partStatus.text = "To Do" + $partStatus.AutoSize = $true + + $statusPanel.controls.add($partLabel, 0, $row) + $statusPanel.controls.add($partStatus, 1, $row) + $row++ + + $dlLabel = New-Object system.Windows.Forms.Label + $dlLabel.text = "Download" + $dlLabel.AutoSize = $true + + $global:dlStatus = New-Object system.Windows.Forms.Label + $dlStatus.text = "To Do" + $dlStatus.AutoSize = $true + + $statusPanel.controls.add($dlLabel, 0, $row) + $statusPanel.controls.add($dlStatus, 1, $row) + $row++ + + $grubLabel = New-Object system.Windows.Forms.Label + $grubLabel.text = "Install Grub" + $grubLabel.AutoSize = $true + + $global:grubStatus = New-Object system.Windows.Forms.Label + $grubStatus.text = "To Do" + $grubStatus.AutoSize = $true + + $statusPanel.controls.add($grubLabel, 0, $row) + $statusPanel.controls.add($grubStatus, 1, $row) + $row++ + + $rebootLabel = New-Object system.Windows.Forms.Label + $rebootLabel.text = "Reboot" + $rebootLabel.AutoSize = $true + + $global:rebootStatus = New-Object system.Windows.Forms.Label + $rebootStatus.text = "To Do" + $rebootStatus.AutoSize = $true + + $statusPanel.controls.add($rebootLabel, 0, $row) + $statusPanel.controls.add($rebootStatus, 1, $row) + $row++ + + $progress.controls.add($statusPanel) + + #TODO: button panel - Abort + $progress.controls.add( (New-Object system.Windows.Forms.Label) ) + + $form.controls.add($progress) + + + # Actions + + $form.add_shown({ + $global:main.enabled = $false + try { + initFields + } finally { + $global:main.enabled = $true + } + $linuxSize.focus() + }) + + $cleanButton.add_click({ + $global:main.enabled = $false + try { + start-process cleanmgr -wait + calcGui + } finally { + $global:main.enabled = $true + } + }) + + $defragButton.add_click({ + $global:main.enabled = $false + try { + start-process dfrgui -wait + calcGui + } finally { + $global:main.enabled = $true + } + }) + + $parterButton.add_click({ + $global:main.enabled = $false + try { + start-process diskmgmt.msc -wait + calcGui + } finally { + $global:main.enabled = $true + } + }) + + $abortButton.add_click( { + $form.close() + }) + + $installButton.add_click({ + if( (checkFields) ) { + $global:main.visible = $false + $global:progress.visible = $true + #TODO: Run as PSJob, remove doevents + [System.Windows.Forms.Application]::DoEvents() + + $global:defragStatus.text = 'In Progress' + [System.Windows.Forms.Application]::DoEvents() + defrag + $global:defragStatus.text = 'Done' + + $global:partStatus.text = 'In Progress' + [System.Windows.Forms.Application]::DoEvents() + repartition + $global:partStatus.text = 'Done' + + $global:dlStatus.text = 'In Progress' + [System.Windows.Forms.Application]::DoEvents() + downloadIso + $global:dlStatus.text = 'Done' + + $global:grubStatus.text = 'In Progress' + [System.Windows.Forms.Application]::DoEvents() + installGrub + $global:grubStatus.text = 'Done' + + $global:rebootStatus.text = 'In Progress' + [System.Windows.Forms.Application]::DoEvents() + Restart-Computer + } + }) + + return $form +} + + +$op = $args[0] + +switch($op) { + {$_ -eq "download-iso" } { + downloadIso + } + {$_ -eq "enable-swap" } { + enableSwap + Restart-Computer + } + {$_ -eq "disable-swap" } { + disableSwap + Restart-Computer + } + {$_ -eq "tz" } { +# getLinuxTimezone + installGrub + } + {$_ -eq "defrag" } { + defrag + } + {$_ -eq "preseed" } { + set-content -value (expandTemplate "files\preseed.cfg") -path "preseed.tmp.cfg" + get-content -path 'preseed.tmp.cfg' + } + default { + $form = (gui) + $form.showDialog() + } +} +