From 97a18f8777d3972aa4e107f8529f4cc110f154f0 Mon Sep 17 00:00:00 2001 From: Ludwig Lehnert Date: Mon, 29 Jun 2026 10:10:46 +0000 Subject: [PATCH] initial commit --- LICENSE | 674 ++++++++++++++++++++ setup.ps1 | 1754 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 2428 insertions(+) create mode 100644 LICENSE create mode 100644 setup.ps1 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/setup.ps1 b/setup.ps1 new file mode 100644 index 0000000..bf9f1ab --- /dev/null +++ b/setup.ps1 @@ -0,0 +1,1754 @@ +<# +SelfServiceWinget.ps1 + +Use as: +- Computer Startup GPO script (default mode = Install) +- Scheduled task target (Mode = Daemon / UpgradeAll) + +Behavior: +User -> GUI / request helper -> named pipe -> daemon task (SYSTEM) -> winget install --scope machine + +Created paths: +C:\ProgramData\__Softwarekatalog\ + SelfServiceWinget.ps1 + Request-App.ps1 + Software-Catalog.ps1 + Launch-Software-Catalog.vbs + Installed-Packages.json + Logs\service.log +#> + +[CmdletBinding()] +param( + [ValidateSet('Install','Daemon','UpgradeAll')] + [string]$Mode = 'Install' +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +# ---------------------------- +# Configuration +# ---------------------------- +$CatalogDisplayName = 'Softwarekatalog' +$BaseDir = Join-Path $env:ProgramData '__Softwarekatalog' +$LocalScriptPath = Join-Path $BaseDir 'SelfServiceWinget.ps1' +$RequestToolPath = Join-Path $BaseDir 'Request-App.ps1' +$CatalogGuiPath = Join-Path $BaseDir 'Software-Catalog.ps1' +$CatalogLauncherPath = Join-Path $BaseDir 'Launch-Software-Catalog.vbs' +$InstalledPackagesPath = Join-Path $BaseDir 'Installed-Packages.json' +$LogDir = Join-Path $BaseDir 'Logs' +$LogFile = Join-Path $LogDir 'service.log' +$LegacyQueueTaskName = 'Softwarekatalog - Winget Queue' +$DaemonTaskName = 'Softwarekatalog - Daemon' +$UpgradeTaskName = 'Softwarekatalog - Winget Upgrade' +$PipeName = 'Softwarekatalog' +$WingetMutexName = 'Global\Softwarekatalog-Winget' +$PowerShellExe = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe' +$WScriptExe = Join-Path $env:SystemRoot 'System32\wscript.exe' +$AppInstallerFamilyName = 'Microsoft.DesktopAppInstaller_8wekyb3d8bbwe' +$CommonDesktopDir = [Environment]::GetFolderPath('CommonDesktopDirectory') +$CommonProgramsDir = [Environment]::GetFolderPath('CommonPrograms') +$DesktopShortcutPath = Join-Path $CommonDesktopDir "$CatalogDisplayName.lnk" +$StartMenuShortcutPath = Join-Path $CommonProgramsDir "$CatalogDisplayName.lnk" + +# App catalog configuration (list-based) +$AllowedApps = @( + [ordered]@{ Alias = 'vscode'; Title = 'Visual Studio Code'; Description = 'Leistungsfähiger Quellcode-Editor mit Erweiterungs-Ökosystem'; PackageId = 'Microsoft.VisualStudioCode' } + [ordered]@{ Alias = 'notepadpp'; Title = 'Notepad++'; Description = 'Schneller Text- und Codeeditor mit Syntax-Highlighting'; PackageId = 'Notepad++.Notepad++' } + [ordered]@{ Alias = 'sevenzip'; Title = '7-Zip'; Description = 'Werkzeug zum Komprimieren und Entpacken von Archivdateien'; PackageId = '7zip.7zip' } + [ordered]@{ Alias = 'adobereader'; Title = 'Adobe Acrobat Reader'; Description = 'Betrachter zum Öffnen, Lesen und Drucken von PDF-Dokumenten'; PackageId = 'Adobe.Acrobat.Reader.64-bit' } + [ordered]@{ Alias = 'vlc'; Title = 'VLC media player'; Description = 'Universeller Open-Source-Player für Audio- und Videoformate'; PackageId = 'VideoLAN.VLC' } + [ordered]@{ Alias = 'git'; Title = 'Git'; Description = 'Verteiltes Versionskontrollsystem für Softwareprojekte'; PackageId = 'Git.Git' } + [ordered]@{ Alias = 'python314'; Title = 'Python 3.14'; Description = 'Interpreter und Laufzeitumgebung für die Programmiersprache Python'; PackageId = 'Python.Python.3.14' } + [ordered]@{ Alias = 'bitwarden'; Title = 'Bitwarden'; Description = 'Open-Source Passwortmanager mit verschlüsseltem Tresor'; PackageId = 'Bitwarden.Bitwarden' } + [ordered]@{ Alias = 'keepass'; Title = 'KeePass'; Description = 'Lokaler Passwortmanager mit verschlüsselter Datenbank'; PackageId = 'DominikReichl.KeePass' } + [ordered]@{ Alias = 'keepassxc'; Title = 'KeePassXC'; Description = 'Moderner Open-Source Passwortmanager mit KeePass-Kompatibilität'; PackageId = 'KeePassXCTeam.KeePassXC' } + [ordered]@{ Alias = 'gimp'; Title = 'GIMP'; Description = 'Open-Source Bildbearbeitungsprogramm für Retusche und Grafikdesign'; PackageId = 'GIMP.GIMP.3' } + [ordered]@{ Alias = 'inkscape'; Title = 'Inkscape'; Description = 'Editor für Vektorgrafiken im SVG-Format'; PackageId = 'Inkscape.Inkscape' } + [ordered]@{ Alias = 'onlyoffice'; Title = 'ONLYOFFICE Desktop Editors'; Description = 'Desktop-Office-Suite für Dokumente, Tabellen und Präsentationen'; PackageId = 'ONLYOFFICE.DesktopEditors' } + [ordered]@{ Alias = 'libreoffice'; Title = 'LibreOffice'; Description = 'Umfangreiche Open-Source-Office-Suite als Microsoft-Office-Alternative'; PackageId = 'TheDocumentFoundation.LibreOffice' } + [ordered]@{ Alias = 'triliumnext'; Title = 'Trilium Notes'; Description = 'Hierarchisches Notizsystem für persönliche Wissensdatenbanken'; PackageId = 'TriliumNext.Notes' } + [ordered]@{ Alias = 'logseq'; Title = 'Logseq'; Description = 'Markdown-basierte Wissens- und Notizverwaltung mit Graphstruktur'; PackageId = 'Logseq.Logseq' } + [ordered]@{ Alias = 'superproductivity'; Title = 'Super Productivity'; Description = 'Aufgaben- und Zeitmanagement mit Fokus auf Entwickler-Workflows'; PackageId = 'JohannesMillan.superProductivity' } + [ordered]@{ Alias = 'typst'; Title = 'Typst'; Description = 'Modernes Satzsystem zum Erstellen technisch formatierter Dokumente'; PackageId = 'Typst.Typst' } + [ordered]@{ Alias = 'thunderbirdde'; Title = 'Mozilla Thunderbird (DE)'; Description = 'E-Mail-Client mit Kalender, Verschlüsselung und Erweiterungen'; PackageId = 'Mozilla.Thunderbird.de' } + [ordered]@{ Alias = 'virtualbox'; Title = 'Oracle VM VirtualBox'; Description = 'Virtualisierungssoftware zum Ausführen mehrerer Betriebssysteme'; PackageId = 'Oracle.VirtualBox' } + [ordered]@{ Alias = 'powershell7'; Title = 'PowerShell 7'; Description = 'Moderne plattformübergreifende PowerShell für Automatisierung und Skripting'; PackageId = 'Microsoft.PowerShell' } + [ordered]@{ Alias = 'windowsterminal'; Title = 'Windows Terminal'; Description = 'Moderner Terminal für PowerShell, CMD, WSL und SSH'; PackageId = 'Microsoft.WindowsTerminal' } + [ordered]@{ Alias = 'nodejs'; Title = 'Node.js LTS'; Description = 'JavaScript-Laufzeitumgebung für Tools und Anwendungen'; PackageId = 'OpenJS.NodeJS.LTS' } + [ordered]@{ Alias = 'everything'; Title = 'Everything'; Description = 'Extrem schnelle Dateisuche für Windows'; PackageId = 'voidtools.Everything' } + [ordered]@{ Alias = 'rufus'; Title = 'Rufus'; Description = 'Tool zum Erstellen bootfähiger USB-Sticks'; PackageId = 'Rufus.Rufus' } + [ordered]@{ Alias = 'filezilla'; Title = 'FileZilla Client'; Description = 'FTP-, FTPS- und SFTP-Client für Dateiübertragungen'; PackageId = 'FileZilla.FileZilla.Client' } + [ordered]@{ Alias = 'obs'; Title = 'OBS Studio'; Description = 'Open-Source Software für Bildschirmaufnahme und Streaming'; PackageId = 'OBSProject.OBSStudio' } + [ordered]@{ Alias = 'powertoys'; Title = 'Microsoft PowerToys'; Description = 'Sammlung nützlicher Produktivitätswerkzeuge für Windows'; PackageId = 'Microsoft.PowerToys' } + [ordered]@{ Alias = 'wireshark'; Title = 'Wireshark'; Description = 'Netzwerkprotokoll-Analyzer zur Analyse von Netzwerkverkehr'; PackageId = 'WiresharkFoundation.Wireshark' } + [ordered]@{ Alias = 'bruno'; Title = 'Bruno'; Description = 'Leichtgewichtiger API-Client zum Testen von REST- und HTTP-APIs'; PackageId = 'usebruno.bruno' } + [ordered]@{ Alias = 'anki'; Title = 'Anki'; Description = 'Karteikartenprogramm für effektives Lernen mit Spaced-Repetition'; PackageId = 'Anki.Anki' } + [ordered]@{ Alias = 'torbrowser'; Title = 'Tor Browser'; Description = 'Datenschutzorientierter Webbrowser für anonymes Surfen über das Tor-Netzwerk'; PackageId = 'TorProject.TorBrowser' } + [ordered]@{ Alias = 'citrixworkspace'; Title = 'Citrix Workspace'; Description = 'Client für den Zugriff auf virtuelle Desktops und Anwendungen über Citrix-Infrastruktur'; PackageId = 'Citrix.Workspace' } + [ordered]@{ Alias = 'msoffice'; Title = 'Microsoft 365 Apps for enterprise'; Description = 'Microsoft Office-Desktopanwendungen wie Word, Excel, PowerPoint und Outlook aus Microsoft 365'; PackageId = 'Microsoft.Office' } +) + +# ---------------------------- +# Utility functions +# ---------------------------- +function Ensure-Directory { + param([Parameter(Mandatory)][string]$Path) + if (-not (Test-Path -LiteralPath $Path)) { + New-Item -ItemType Directory -Path $Path -Force | Out-Null + } +} + +function Write-Log { + param( + [Parameter(Mandatory)][string]$Message, + [ValidateSet('INFO','WARN','ERROR')] + [string]$Level = 'INFO' + ) + + Ensure-Directory -Path $LogDir + $line = '{0} [{1}] {2}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $Level, $Message + Add-Content -LiteralPath $LogFile -Value $line -Encoding UTF8 +} + +function Set-DirectoryAcl { + param( + [Parameter(Mandatory)][string]$Path, + [Parameter(Mandatory)][bool]$UsersCanModify + ) + + $inheritance = [System.Security.AccessControl.InheritanceFlags]'ContainerInherit, ObjectInherit' + $propagation = [System.Security.AccessControl.PropagationFlags]::None + + $acl = New-Object System.Security.AccessControl.DirectorySecurity + $acl.SetAccessRuleProtection($true, $false) + + $sidSystem = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-18') + $sidAdmins = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-544') + $sidUsers = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-545') + + $ruleSystem = New-Object System.Security.AccessControl.FileSystemAccessRule( + $sidSystem, 'FullControl', $inheritance, $propagation, 'Allow' + ) + $ruleAdmins = New-Object System.Security.AccessControl.FileSystemAccessRule( + $sidAdmins, 'FullControl', $inheritance, $propagation, 'Allow' + ) + + if ($UsersCanModify) { + $ruleUsers = New-Object System.Security.AccessControl.FileSystemAccessRule( + $sidUsers, 'Modify', $inheritance, $propagation, 'Allow' + ) + } + else { + $ruleUsers = New-Object System.Security.AccessControl.FileSystemAccessRule( + $sidUsers, 'ReadAndExecute, Synchronize', $inheritance, $propagation, 'Allow' + ) + } + + $null = $acl.AddAccessRule($ruleSystem) + $null = $acl.AddAccessRule($ruleAdmins) + $null = $acl.AddAccessRule($ruleUsers) + + Set-Acl -LiteralPath $Path -AclObject $acl +} + +function Set-FileAclAdminsOnly { + param([Parameter(Mandatory)][string]$Path) + + $acl = New-Object System.Security.AccessControl.FileSecurity + $acl.SetAccessRuleProtection($true, $false) + + $sidSystem = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-18') + $sidAdmins = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-544') + $sidUsers = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-545') + + $ruleSystem = New-Object System.Security.AccessControl.FileSystemAccessRule( + $sidSystem, 'FullControl', 'Allow' + ) + $ruleAdmins = New-Object System.Security.AccessControl.FileSystemAccessRule( + $sidAdmins, 'FullControl', 'Allow' + ) + $ruleUsers = New-Object System.Security.AccessControl.FileSystemAccessRule( + $sidUsers, 'ReadAndExecute, Synchronize', 'Allow' + ) + + $null = $acl.AddAccessRule($ruleSystem) + $null = $acl.AddAccessRule($ruleAdmins) + $null = $acl.AddAccessRule($ruleUsers) + + Set-Acl -LiteralPath $Path -AclObject $acl +} + +function Get-AppCatalogObjects { + foreach ($app in $AllowedApps) { + [pscustomobject]@{ + Alias = [string]$app.Alias + DisplayName = [string]$app.Title + Description = [string]$app.Description + PackageId = [string]$app.PackageId + } + } +} + +function Get-PackageIdByAlias { + param([Parameter(Mandatory)][string]$Alias) + + foreach ($app in $AllowedApps) { + if ([string]::Equals([string]$app.Alias, $Alias, [System.StringComparison]::OrdinalIgnoreCase)) { + return [string]$app.PackageId + } + } + + return $null +} + +function Write-TextFile { + param( + [Parameter(Mandatory)][string]$Path, + [Parameter(Mandatory)][string]$Content, + [ValidateSet('Utf8Bom','Unicode')] + [string]$Encoding = 'Utf8Bom' + ) + + $parent = Split-Path -Path $Path -Parent + if ($parent) { + Ensure-Directory -Path $parent + } + + switch ($Encoding) { + 'Unicode' { $textEncoding = New-Object System.Text.UnicodeEncoding($false, $true) } + default { $textEncoding = New-Object System.Text.UTF8Encoding($true) } + } + + [System.IO.File]::WriteAllText($Path, $Content, $textEncoding) +} + +function Invoke-WithWingetLock { + param( + [Parameter(Mandatory)][scriptblock]$ScriptBlock, + [int]$TimeoutSeconds = 7200 + ) + + $mutex = New-Object System.Threading.Mutex($false, $WingetMutexName) + $hasLock = $false + + try { + $hasLock = $mutex.WaitOne([TimeSpan]::FromSeconds($TimeoutSeconds)) + if (-not $hasLock) { + throw "Timed out waiting for winget lock '$WingetMutexName'." + } + + & $ScriptBlock + } + finally { + if ($hasLock) { + $mutex.ReleaseMutex() + } + $mutex.Dispose() + } +} + +function Get-WingetPath { + $candidates = @() + + try { + $cmd = Get-Command winget.exe -ErrorAction Stop + if ($cmd -and $cmd.Source) { + $candidates += $cmd.Source + } + } + catch { + } + + try { + $packages = Get-AppxPackage -AllUsers -Name Microsoft.DesktopAppInstaller -ErrorAction Stop | + Where-Object { $_.InstallLocation } | + Sort-Object Version -Descending + + foreach ($package in $packages) { + $candidate = Join-Path $package.InstallLocation 'winget.exe' + if (Test-Path -LiteralPath $candidate) { + $candidates += $candidate + } + } + } + catch { + } + + $windowsAppsRoot = Join-Path $env:ProgramFiles 'WindowsApps' + if (Test-Path -LiteralPath $windowsAppsRoot) { + try { + $items = Get-ChildItem -LiteralPath $windowsAppsRoot -Directory -ErrorAction Stop | + Where-Object { $_.Name -like 'Microsoft.DesktopAppInstaller_*_8wekyb3d8bbwe' } | + Sort-Object Name -Descending + + foreach ($item in $items) { + $candidate = Join-Path $item.FullName 'winget.exe' + if (Test-Path -LiteralPath $candidate) { + $candidates += $candidate + } + } + } + catch { + } + } + + $resolved = $candidates | Select-Object -Unique | Select-Object -First 1 + return $resolved +} + +function Ensure-WingetAvailable { + $wingetPath = Get-WingetPath + if ($wingetPath) { + Write-Log "winget already available at: $wingetPath" + return $wingetPath + } + + Write-Log 'winget.exe not found.' + + $isLocalSystem = $false + try { + $isLocalSystem = [System.Security.Principal.WindowsIdentity]::GetCurrent().IsSystem + } + catch { + } + + if ($isLocalSystem) { + Write-Log "App Installer package registration cannot run as LocalSystem; skipping Add-AppxPackage fallback for '$AppInstallerFamilyName'." 'ERROR' + Write-Log 'winget is unavailable. Install/provision App Installer, or verify winget path discovery for this device.' 'ERROR' + return $null + } + + Write-Log "Attempting to register App Installer package family '$AppInstallerFamilyName'." + + try { + Add-AppxPackage -RegisterByFamilyName -MainPackage $AppInstallerFamilyName + Start-Sleep -Seconds 3 + } + catch { + Write-Log "Add-AppxPackage registration attempt failed: $($_.Exception.Message)" 'ERROR' + } + + $wingetPath = Get-WingetPath + if ($wingetPath) { + Write-Log "winget became available after App Installer registration: $wingetPath" + return $wingetPath + } + + Write-Log "winget is still unavailable after App Installer registration attempt." 'ERROR' + return $null +} + +function New-UserRequestTool { + $appsJson = (Get-AppCatalogObjects | ConvertTo-Json -Depth 4) + $pipeLiteral = $PipeName.Replace("'", "''") + +$content = @" +[CmdletBinding()] +param( + [string]`$AppAlias, + [ValidateSet('Install','Uninstall')] + [string]`$Action = 'Install', + [switch]`$Uninstall, + [switch]`$List +) + +Set-StrictMode -Version Latest +`$ErrorActionPreference = 'Stop' + +`$AppsJson = @' +$appsJson +'@ + +`$Apps = `$AppsJson | ConvertFrom-Json +`$AllowedAliases = @(`$Apps | ForEach-Object { `$_.Alias }) +`$PipeName = '$pipeLiteral' + +function Invoke-CatalogDaemon { + param( + [Parameter(Mandatory=`$true)][string]`$Command, + [string]`$Alias + ) + + `$payload = [ordered]@{ + Command = `$Command + AppAlias = `$Alias + } + `$json = `$payload | ConvertTo-Json -Compress + + `$encoding = New-Object System.Text.UTF8Encoding(`$false) + `$client = New-Object System.IO.Pipes.NamedPipeClientStream -ArgumentList @( + '.', + `$PipeName, + [System.IO.Pipes.PipeDirection]::InOut, + [System.IO.Pipes.PipeOptions]::None, + [System.Security.Principal.TokenImpersonationLevel]::Impersonation + ) + + try { + `$client.Connect(30000) + `$reader = New-Object System.IO.StreamReader(`$client, `$encoding) + `$writer = New-Object System.IO.StreamWriter(`$client, `$encoding) + `$writer.AutoFlush = `$true + `$writer.WriteLine(`$json) + + `$line = `$reader.ReadLine() + if ([string]::IsNullOrWhiteSpace(`$line)) { + throw 'Der Softwarekatalog-Dienst hat keine Antwort gesendet.' + } + + `$response = `$line | ConvertFrom-Json + if (-not `$response.Success) { + throw ([string]`$response.Message) + } + + return `$response + } + finally { + `$client.Dispose() + } +} + +if (`$Uninstall) { + `$Action = 'Uninstall' +} + +if (`$List) { + Write-Host 'Freigegebene Anwendungen:' + `$Apps | Sort-Object DisplayName | ForEach-Object { + Write-Host (" - {0} [{1}] : {2}" -f `$_.DisplayName, `$_.Alias, `$_.Description) + } + exit 0 +} + +if (-not `$AppAlias) { + throw 'Sie müssen -AppAlias angeben oder -List verwenden.' +} + +`$alias = `$AppAlias.Trim().ToLowerInvariant() +if (`$AllowedAliases -notcontains `$alias) { + throw "App-Alias '`$AppAlias' ist nicht freigegeben. Mit -List sehen Sie gültige Aliase." +} + +`$response = Invoke-CatalogDaemon -Command `$Action -Alias `$alias + +if (`$Action -eq 'Uninstall') { + Write-Host "Deinstallation für '`$alias' abgeschlossen." +} +else { + Write-Host "Installation für '`$alias' abgeschlossen." +} + +if (`$response.Message) { + Write-Host `$response.Message +} +"@ + + Write-TextFile -Path $RequestToolPath -Content $content -Encoding Utf8Bom + Set-FileAclAdminsOnly -Path $RequestToolPath +} + +function New-CatalogGui { + $appsJson = (Get-AppCatalogObjects | ConvertTo-Json -Depth 4) + $pipeLiteral = $PipeName.Replace("'", "''") + $titleLiteral = $CatalogDisplayName.Replace("'", "''") + $logLiteral = $LogFile.Replace("'", "''") + $installedLiteral = $InstalledPackagesPath.Replace("'", "''") + +$content = @" +Add-Type -AssemblyName System.Windows.Forms +Add-Type -AssemblyName System.Drawing +[System.Windows.Forms.Application]::EnableVisualStyles() + +if (-not ('ListViewColumnSorter' -as [type])) { +Add-Type -TypeDefinition @' +using System; +using System.Collections; +using System.Windows.Forms; + +public class ListViewColumnSorter : IComparer { + public int Column = 0; + public SortOrder Order = SortOrder.Ascending; + + public int Compare(object x, object y) { + var itemX = x as ListViewItem; + var itemY = y as ListViewItem; + string a = string.Empty; + string b = string.Empty; + + if (itemX != null && itemX.SubItems.Count > Column) { + a = itemX.SubItems[Column].Text; + } + if (itemY != null && itemY.SubItems.Count > Column) { + b = itemY.SubItems[Column].Text; + } + + int result = StringComparer.CurrentCultureIgnoreCase.Compare(a, b); + return Order == SortOrder.Descending ? -result : result; + } +} +'@ -ReferencedAssemblies @('System.dll','System.Windows.Forms.dll') +} + +if (-not ('ShellIconExtractor' -as [type])) { +Add-Type -TypeDefinition @' +using System; +using System.Runtime.InteropServices; + +public static class ShellIconExtractor { + [DllImport("shell32.dll", CharSet = CharSet.Unicode)] + public static extern uint ExtractIconEx(string szFileName, int nIconIndex, IntPtr[] phiconLarge, IntPtr[] phiconSmall, uint nIcons); + + [DllImport("user32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] +public static extern bool DestroyIcon(IntPtr hIcon); +} +'@ +} + +Set-StrictMode -Version Latest +`$ErrorActionPreference = 'Stop' + +`$AppsJson = @' +$appsJson +'@ + +`$Apps = `$AppsJson | ConvertFrom-Json +`$PipeName = '$pipeLiteral' +`$CatalogTitle = '$titleLiteral' +`$LogFile = '$logLiteral' +`$InstalledPackagesPath = '$installedLiteral' + +function Set-FormIcon { + param([Parameter(Mandatory=`$true)]`$Form) + + `$large = `$null + `$small = `$null + + try { + `$iconFile = Join-Path `$env:SystemRoot 'System32\shell32.dll' + `$large = New-Object System.IntPtr[] 1 + `$small = New-Object System.IntPtr[] 1 + `$count = [ShellIconExtractor]::ExtractIconEx(`$iconFile, 80, `$large, `$small, 1) + + if (`$count -gt 0) { + `$useHandle = [IntPtr]::Zero + if (`$small[0] -ne [IntPtr]::Zero) { + `$useHandle = `$small[0] + } + elseif (`$large[0] -ne [IntPtr]::Zero) { + `$useHandle = `$large[0] + } + + if (`$useHandle -ne [IntPtr]::Zero) { + `$icon = [System.Drawing.Icon]::FromHandle(`$useHandle) + `$Form.Icon = [System.Drawing.Icon]`$icon.Clone() + } + } + } + catch { + } + finally { + try { + if (`$small -and `$small[0] -ne [IntPtr]::Zero) { + [void][ShellIconExtractor]::DestroyIcon(`$small[0]) + } + } + catch { + } + + try { + if (`$large -and `$large[0] -ne [IntPtr]::Zero) { + [void][ShellIconExtractor]::DestroyIcon(`$large[0]) + } + } + catch { + } + } +} + +function Invoke-CatalogDaemon { + param( + [Parameter(Mandatory=`$true)][string]`$Command, + [string]`$Alias + ) + + `$payload = [ordered]@{ + Command = `$Command + AppAlias = `$Alias + } + `$json = `$payload | ConvertTo-Json -Compress + + `$encoding = New-Object System.Text.UTF8Encoding(`$false) + `$client = New-Object System.IO.Pipes.NamedPipeClientStream -ArgumentList @( + '.', + `$PipeName, + [System.IO.Pipes.PipeDirection]::InOut, + [System.IO.Pipes.PipeOptions]::None, + [System.Security.Principal.TokenImpersonationLevel]::Impersonation + ) + + try { + `$client.Connect(30000) + `$reader = New-Object System.IO.StreamReader(`$client, `$encoding) + `$writer = New-Object System.IO.StreamWriter(`$client, `$encoding) + `$writer.AutoFlush = `$true + `$writer.WriteLine(`$json) + + `$line = `$reader.ReadLine() + if ([string]::IsNullOrWhiteSpace(`$line)) { + throw 'Der Softwarekatalog-Dienst hat keine Antwort gesendet.' + } + + `$response = `$line | ConvertFrom-Json + if (-not `$response.Success) { + throw ([string]`$response.Message) + } + + return `$response + } + finally { + `$client.Dispose() + } +} + +function New-AppRequest { + param( + [Parameter(Mandatory=`$true)][string]`$Alias, + [Parameter(Mandatory=`$true)][ValidateSet('Install','Uninstall')][string]`$Action + ) + + return Invoke-CatalogDaemon -Command `$Action -Alias (`$Alias.Trim().ToLowerInvariant()) +} + +function Get-InstalledPackageState { + `$state = [ordered]@{ + GeneratedAt = `$null + PackageSet = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase) + } + + if (-not (Test-Path -LiteralPath `$InstalledPackagesPath)) { + return [pscustomobject]`$state + } + + try { + `$raw = Get-Content -LiteralPath `$InstalledPackagesPath -Raw -Encoding UTF8 + if ([string]::IsNullOrWhiteSpace(`$raw)) { + return [pscustomobject]`$state + } + + `$snapshot = `$raw | ConvertFrom-Json + if (`$snapshot.GeneratedAt) { + `$state.GeneratedAt = [string]`$snapshot.GeneratedAt + } + + foreach (`$id in @(`$snapshot.InstalledPackageIds)) { + if (`$id) { + [void]`$state.PackageSet.Add(([string]`$id).Trim()) + } + } + } + catch { + } + + return [pscustomobject]`$state +} + +function Get-AppStatus { + param( + [Parameter(Mandatory=`$true)]`$App, + [Parameter(Mandatory=`$true)]`$InstalledSet + ) + + if (`$InstalledSet.Contains(`$App.PackageId)) { + return 'Installiert' + } + + return 'Installierbar' +} + +`$form = New-Object System.Windows.Forms.Form +`$form.Text = `$CatalogTitle +`$form.StartPosition = 'CenterScreen' +`$form.Size = New-Object System.Drawing.Size(980, 660) +`$form.MinimumSize = New-Object System.Drawing.Size(960, 640) +`$form.TopMost = `$false +`$form.ShowIcon = `$true +`$form.Font = New-Object System.Drawing.Font('Segoe UI', 9) +`$form.BackColor = [System.Drawing.ColorTranslator]::FromHtml('#F3F3F3') +Set-FormIcon -Form `$form + +`$headerPanel = New-Object System.Windows.Forms.Panel +`$headerPanel.Location = New-Object System.Drawing.Point(12, 12) +`$headerPanel.Size = New-Object System.Drawing.Size(940, 84) +`$headerPanel.Anchor = 'Top, Left, Right' +`$headerPanel.BackColor = [System.Drawing.SystemColors]::Window +`$headerPanel.BorderStyle = 'FixedSingle' + +`$headerAccent = New-Object System.Windows.Forms.Panel +`$headerAccent.Location = New-Object System.Drawing.Point(0, 0) +`$headerAccent.Size = New-Object System.Drawing.Size(6, 82) +`$headerAccent.Anchor = 'Top, Left, Bottom' +`$headerAccent.BackColor = [System.Drawing.ColorTranslator]::FromHtml('#0F6CBD') + +`$headerTitle = New-Object System.Windows.Forms.Label +`$headerTitle.Location = New-Object System.Drawing.Point(18, 12) +`$headerTitle.Size = New-Object System.Drawing.Size(900, 24) +`$headerTitle.Font = New-Object System.Drawing.Font('Segoe UI Semibold', 13) +`$headerTitle.Text = `$CatalogTitle + +`$headerPanel.Controls.Add(`$headerAccent) +`$headerPanel.Controls.Add(`$headerTitle) + +`$groupApps = New-Object System.Windows.Forms.Panel +`$groupApps.Location = New-Object System.Drawing.Point(12, 104) +`$groupApps.Size = New-Object System.Drawing.Size(940, 352) +`$groupApps.Anchor = 'Top, Left, Right, Bottom' +`$groupApps.BackColor = [System.Drawing.SystemColors]::Window +`$groupApps.BorderStyle = 'FixedSingle' + +`$listCaption = New-Object System.Windows.Forms.Label +`$listCaption.Location = New-Object System.Drawing.Point(12, 10) +`$listCaption.Size = New-Object System.Drawing.Size(912, 20) +`$listCaption.Font = New-Object System.Drawing.Font('Segoe UI Semibold', 9.5) +`$listCaption.Text = 'Freigegebene Anwendungen' + +`$list = New-Object System.Windows.Forms.ListView +`$list.Location = New-Object System.Drawing.Point(12, 34) +`$list.Size = New-Object System.Drawing.Size(916, 306) +`$list.Anchor = 'Top, Left, Right, Bottom' +`$list.View = 'Details' +`$list.FullRowSelect = `$true +`$list.MultiSelect = `$false +`$list.GridLines = `$false +`$list.HideSelection = `$false +[void]`$list.Columns.Add('Anwendung', 260) +[void]`$list.Columns.Add('Beschreibung', 450) +[void]`$list.Columns.Add('Status', 150) +[void]`$list.Columns.Add('Alias', 110) +[void]`$list.Columns.Add('Paket-ID', 100) +`$list.BorderStyle = 'None' +`$list.HeaderStyle = 'Clickable' + +`$columnSorter = New-Object ListViewColumnSorter +`$list.ListViewItemSorter = `$columnSorter + +function Sort-ListByColumn { + param([Parameter(Mandatory=`$true)][int]`$ColumnIndex) + + if (`$columnSorter.Column -eq `$ColumnIndex) { + if (`$columnSorter.Order -eq [System.Windows.Forms.SortOrder]::Ascending) { + `$columnSorter.Order = [System.Windows.Forms.SortOrder]::Descending + } + else { + `$columnSorter.Order = [System.Windows.Forms.SortOrder]::Ascending + } + } + else { + `$columnSorter.Column = `$ColumnIndex + `$columnSorter.Order = [System.Windows.Forms.SortOrder]::Ascending + } + + `$list.Sort() +} + +`$groupApps.Controls.Add(`$listCaption) +`$groupApps.Controls.Add(`$list) + +`$infoPanel = New-Object System.Windows.Forms.Panel +`$infoPanel.Location = New-Object System.Drawing.Point(12, 466) +`$infoPanel.Size = New-Object System.Drawing.Size(940, 64) +`$infoPanel.Anchor = 'Left, Right, Bottom' +`$infoPanel.BorderStyle = 'FixedSingle' +`$infoPanel.BackColor = [System.Drawing.SystemColors]::Window + +`$snapshotLabel = New-Object System.Windows.Forms.Label +`$snapshotLabel.Location = New-Object System.Drawing.Point(10, 8) +`$snapshotLabel.Size = New-Object System.Drawing.Size(914, 18) +`$snapshotLabel.Text = 'Installationsdaten: kein Datenstand vorhanden' + +`$installedLabel = New-Object System.Windows.Forms.Label +`$installedLabel.Location = New-Object System.Drawing.Point(10, 30) +`$installedLabel.Size = New-Object System.Drawing.Size(914, 24) +`$installedLabel.Text = 'Bereits installiert: keine' + +`$infoPanel.Controls.Add(`$snapshotLabel) +`$infoPanel.Controls.Add(`$installedLabel) + +function Update-InstallButtonState { + if (`$list.SelectedItems.Count -lt 1) { + `$btnInstall.Enabled = `$false + `$btnUninstall.Enabled = `$false + return + } + + `$selectedItem = `$list.SelectedItems[0] + `$state = `$selectedItem.SubItems[2].Text + + `$btnInstall.Enabled = (`$state -eq 'Installierbar') + `$btnUninstall.Enabled = (`$state -eq 'Installiert') +} + +function Load-AppList { + `$selectedAlias = `$null + `$list.BeginUpdate() + try { + if (`$list.SelectedItems.Count -gt 0) { + `$selectedAlias = [string]`$list.SelectedItems[0].SubItems[3].Text + } + + `$list.Items.Clear() + + `$installedState = Get-InstalledPackageState + `$installedSet = `$installedState.PackageSet + + if (-not `$installedSet) { + `$installedSet = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase) + } + + `$installedNames = New-Object 'System.Collections.Generic.List[string]' + + foreach (`$app in (`$Apps | Sort-Object DisplayName)) { + `$state = Get-AppStatus -App `$app -InstalledSet `$installedSet + + `$item = New-Object System.Windows.Forms.ListViewItem(`$app.DisplayName) + [void]`$item.SubItems.Add(`$app.Description) + [void]`$item.SubItems.Add(`$state) + [void]`$item.SubItems.Add(`$app.Alias) + [void]`$item.SubItems.Add(`$app.PackageId) + `$item.Tag = `$app + + if (`$state -eq 'Installiert') { + `$item.ForeColor = [System.Drawing.Color]::DarkGreen + [void]`$installedNames.Add(`$app.DisplayName) + } + + [void]`$list.Items.Add(`$item) + } + + foreach (`$col in `$list.Columns) { + if (`$col.Text -eq 'Paket-ID') { `$col.Width = 0 } + } + + `$list.Sort() + + if (`$installedState.GeneratedAt) { + try { + `$timestamp = [DateTime]::Parse(`$installedState.GeneratedAt).ToLocalTime() + `$snapshotLabel.Text = 'Installationsdaten vom: ' + `$timestamp.ToString('dd.MM.yyyy HH:mm:ss') + } + catch { + `$snapshotLabel.Text = 'Installationsdaten vom: ' + `$installedState.GeneratedAt + } + } + else { + `$snapshotLabel.Text = 'Installationsdaten: kein Datenstand vorhanden' + } + + if (`$installedNames.Count -gt 0) { + `$installedLabel.Text = 'Bereits installiert: ' + (`$installedNames -join ', ') + } + else { + `$installedLabel.Text = 'Bereits installiert: keine freigegebene Software erkannt' + } + + `$status.Text = 'Liste aktualisiert.' + } + finally { + `$list.EndUpdate() + + if (-not [string]::IsNullOrWhiteSpace(`$selectedAlias)) { + foreach (`$item in `$list.Items) { + if (`$item.SubItems.Count -gt 3 -and [string]::Equals(`$item.SubItems[3].Text, `$selectedAlias, [System.StringComparison]::OrdinalIgnoreCase)) { + `$item.Selected = `$true + `$item.EnsureVisible() + break + } + } + } + + Update-InstallButtonState + } +} + +`$status = New-Object System.Windows.Forms.Label +`$status.Location = New-Object System.Drawing.Point(12, 544) +`$status.Size = New-Object System.Drawing.Size(700, 20) +`$status.Anchor = 'Left, Right, Bottom' +`$status.ForeColor = [System.Drawing.Color]::DimGray +`$status.Text = 'Bereit.' + +`$btnInstall = New-Object System.Windows.Forms.Button +`$btnInstall.Location = New-Object System.Drawing.Point(12, 568) +`$btnInstall.Size = New-Object System.Drawing.Size(170, 30) +`$btnInstall.Anchor = 'Left, Bottom' +`$btnInstall.Text = 'Installieren' +`$btnInstall.Enabled = `$false + +`$btnUninstall = New-Object System.Windows.Forms.Button +`$btnUninstall.Location = New-Object System.Drawing.Point(190, 568) +`$btnUninstall.Size = New-Object System.Drawing.Size(140, 30) +`$btnUninstall.Anchor = 'Left, Bottom' +`$btnUninstall.Text = 'Deinstallation' +`$btnUninstall.Enabled = `$false + +`$btnRefresh = New-Object System.Windows.Forms.Button +`$btnRefresh.Location = New-Object System.Drawing.Point(338, 568) +`$btnRefresh.Size = New-Object System.Drawing.Size(110, 30) +`$btnRefresh.Anchor = 'Left, Bottom' +`$btnRefresh.Text = 'Aktualisieren' + +`$btnOpenLog = New-Object System.Windows.Forms.Button +`$btnOpenLog.Location = New-Object System.Drawing.Point(456, 568) +`$btnOpenLog.Size = New-Object System.Drawing.Size(130, 30) +`$btnOpenLog.Anchor = 'Left, Bottom' +`$btnOpenLog.Text = 'Protokoll öffnen' + +`$btnClose = New-Object System.Windows.Forms.Button +`$btnClose.Location = New-Object System.Drawing.Point(832, 568) +`$btnClose.Size = New-Object System.Drawing.Size(120, 30) +`$btnClose.Anchor = 'Right, Bottom' +`$btnClose.Text = 'Schließen' + +`$autoRefreshTimer = New-Object System.Windows.Forms.Timer +`$autoRefreshTimer.Interval = 15000 + +`$btnInstall.Add_Click({ + try { + if (`$list.SelectedItems.Count -lt 1) { + [System.Windows.Forms.MessageBox]::Show( + 'Bitte zuerst eine Anwendung auswählen.', + `$CatalogTitle, + [System.Windows.Forms.MessageBoxButtons]::OK, + [System.Windows.Forms.MessageBoxIcon]::Information + ) | Out-Null + return + } + + `$selectedItem = `$list.SelectedItems[0] + `$selected = `$selectedItem.Tag + `$currentState = `$selectedItem.SubItems[2].Text + + if (`$currentState -eq 'Installiert') { + [System.Windows.Forms.MessageBox]::Show( + ("{0} ist bereits installiert." -f `$selected.DisplayName), + `$CatalogTitle, + [System.Windows.Forms.MessageBoxButtons]::OK, + [System.Windows.Forms.MessageBoxIcon]::Information + ) | Out-Null + return + } + + `$status.Text = "Installation läuft: {0}" -f `$selected.DisplayName + `$response = New-AppRequest -Alias `$selected.Alias -Action 'Install' + `$status.Text = if (`$response.Message) { `$response.Message } else { "Installation abgeschlossen: {0}" -f `$selected.DisplayName } + + [System.Windows.Forms.MessageBox]::Show( + ("Installation abgeschlossen:`r`n`r`n{0}`r`nAlias: {1}" -f `$selected.DisplayName, `$selected.Alias), + `$CatalogTitle, + [System.Windows.Forms.MessageBoxButtons]::OK, + [System.Windows.Forms.MessageBoxIcon]::Information + ) | Out-Null + + Load-AppList + } + catch { + `$status.Text = "Fehler: " + `$_.Exception.Message + [System.Windows.Forms.MessageBox]::Show( + `$_.Exception.Message, + `$CatalogTitle, + [System.Windows.Forms.MessageBoxButtons]::OK, + [System.Windows.Forms.MessageBoxIcon]::Error + ) | Out-Null + } +}) + +`$btnUninstall.Add_Click({ + try { + if (`$list.SelectedItems.Count -lt 1) { + [System.Windows.Forms.MessageBox]::Show( + 'Bitte zuerst eine Anwendung auswählen.', + `$CatalogTitle, + [System.Windows.Forms.MessageBoxButtons]::OK, + [System.Windows.Forms.MessageBoxIcon]::Information + ) | Out-Null + return + } + + `$selectedItem = `$list.SelectedItems[0] + `$selected = `$selectedItem.Tag + `$currentState = `$selectedItem.SubItems[2].Text + + if (`$currentState -ne 'Installiert') { + [System.Windows.Forms.MessageBox]::Show( + ("{0} ist derzeit nicht als installiert markiert." -f `$selected.DisplayName), + `$CatalogTitle, + [System.Windows.Forms.MessageBoxButtons]::OK, + [System.Windows.Forms.MessageBoxIcon]::Information + ) | Out-Null + return + } + + `$status.Text = "Deinstallation läuft: {0}" -f `$selected.DisplayName + `$response = New-AppRequest -Alias `$selected.Alias -Action 'Uninstall' + `$status.Text = if (`$response.Message) { `$response.Message } else { "Deinstallation abgeschlossen: {0}" -f `$selected.DisplayName } + + [System.Windows.Forms.MessageBox]::Show( + ("Deinstallation abgeschlossen:`r`n`r`n{0}`r`nAlias: {1}" -f `$selected.DisplayName, `$selected.Alias), + `$CatalogTitle, + [System.Windows.Forms.MessageBoxButtons]::OK, + [System.Windows.Forms.MessageBoxIcon]::Information + ) | Out-Null + + Load-AppList + } + catch { + `$status.Text = "Fehler: " + `$_.Exception.Message + [System.Windows.Forms.MessageBox]::Show( + `$_.Exception.Message, + `$CatalogTitle, + [System.Windows.Forms.MessageBoxButtons]::OK, + [System.Windows.Forms.MessageBoxIcon]::Error + ) | Out-Null + } +}) + +`$btnRefresh.Add_Click({ + try { + `$status.Text = 'Installationsdaten werden aktualisiert...' + `$null = Invoke-CatalogDaemon -Command 'RefreshStatus' + Load-AppList + } + catch { + `$status.Text = "Fehler: " + `$_.Exception.Message + [System.Windows.Forms.MessageBox]::Show( + `$_.Exception.Message, + `$CatalogTitle, + [System.Windows.Forms.MessageBoxButtons]::OK, + [System.Windows.Forms.MessageBoxIcon]::Error + ) | Out-Null + } +}) + +`$autoRefreshTimer.Add_Tick({ + try { + Load-AppList + } + catch { + `$status.Text = "Fehler bei automatischer Aktualisierung: " + `$_.Exception.Message + } +}) + +`$btnOpenLog.Add_Click({ + try { + if ([string]::IsNullOrWhiteSpace(`$LogFile)) { + throw 'Der Pfad zur Protokolldatei ist leer.' + } + + if (Test-Path -LiteralPath `$LogFile) { + Start-Process -FilePath 'notepad.exe' -ArgumentList @(`$LogFile) + } + else { + [System.Windows.Forms.MessageBox]::Show( + 'Die Protokolldatei wurde noch nicht erstellt.', + `$CatalogTitle, + [System.Windows.Forms.MessageBoxButtons]::OK, + [System.Windows.Forms.MessageBoxIcon]::Information + ) | Out-Null + } + } + catch { + [System.Windows.Forms.MessageBox]::Show( + `$_.Exception.Message, + `$CatalogTitle, + [System.Windows.Forms.MessageBoxButtons]::OK, + [System.Windows.Forms.MessageBoxIcon]::Error + ) | Out-Null + } +}) + +`$btnClose.Add_Click({ `$form.Close() }) + +`$form.Add_Shown({ `$autoRefreshTimer.Start() }) +`$form.Add_FormClosing({ + `$autoRefreshTimer.Stop() + `$autoRefreshTimer.Dispose() +}) + +`$list.Add_SelectedIndexChanged({ Update-InstallButtonState }) +`$list.Add_ColumnClick({ + param(`$sender, `$eventArgs) + Sort-ListByColumn -ColumnIndex `$eventArgs.Column +}) + +`$list.Add_DoubleClick({ + if (`$list.SelectedItems.Count -gt 0) { + if (`$btnInstall.Enabled) { + `$btnInstall.PerformClick() + } + } +}) + +`$form.Controls.Add(`$headerPanel) +`$form.Controls.Add(`$groupApps) +`$form.Controls.Add(`$infoPanel) +`$form.Controls.Add(`$status) +`$form.Controls.Add(`$btnInstall) +`$form.Controls.Add(`$btnUninstall) +`$form.Controls.Add(`$btnRefresh) +`$form.Controls.Add(`$btnOpenLog) +`$form.Controls.Add(`$btnClose) + +`$form.AcceptButton = `$btnInstall +`$form.CancelButton = `$btnClose + +try { + `$null = Invoke-CatalogDaemon -Command 'RefreshStatus' + Load-AppList +} +catch { + `$status.Text = "Fehler beim Laden: " + `$_.Exception.Message + [System.Windows.Forms.MessageBox]::Show( + "Der Softwarekatalog konnte nicht vollständig geladen werden.`r`n`r`n" + `$_.Exception.Message, + `$CatalogTitle, + [System.Windows.Forms.MessageBoxButtons]::OK, + [System.Windows.Forms.MessageBoxIcon]::Error + ) | Out-Null +} + +[void]`$form.ShowDialog() +"@ + + Write-TextFile -Path $CatalogGuiPath -Content $content -Encoding Utf8Bom + Set-FileAclAdminsOnly -Path $CatalogGuiPath +} + +function New-CatalogLauncher { + $psQuoted = $PowerShellExe.Replace('"', '""') + $guiQuoted = $CatalogGuiPath.Replace('"', '""') + + $vbs = @" +Set shell = CreateObject("WScript.Shell") +cmdLine = Chr(34) & "$psQuoted" & Chr(34) & " -NoProfile -ExecutionPolicy Bypass -STA -WindowStyle Hidden -File " & Chr(34) & "$guiQuoted" & Chr(34) +shell.Run cmdLine, 0, False +"@ + + Write-TextFile -Path $CatalogLauncherPath -Content $vbs -Encoding Unicode + Set-FileAclAdminsOnly -Path $CatalogLauncherPath +} + +function New-Shortcut { + param( + [Parameter(Mandatory)][string]$ShortcutPath + ) + + $parent = Split-Path -Path $ShortcutPath -Parent + Ensure-Directory -Path $parent + + $shell = New-Object -ComObject WScript.Shell + $shortcut = $shell.CreateShortcut($ShortcutPath) + $shortcut.TargetPath = $WScriptExe + $shortcut.Arguments = "`"$CatalogLauncherPath`"" + $shortcut.WorkingDirectory = $BaseDir + $shortcut.WindowStyle = 1 + $shortcut.Description = $CatalogDisplayName + $shortcut.IconLocation = "$env:SystemRoot\System32\shell32.dll,80" + $shortcut.Save() +} + +function Unregister-LegacyQueueTask { + try { + $task = Get-ScheduledTask -TaskName $LegacyQueueTaskName -ErrorAction SilentlyContinue + if ($task) { + Write-Log "Removing legacy scheduled task '$LegacyQueueTaskName'." + Unregister-ScheduledTask -TaskName $LegacyQueueTaskName -Confirm:$false + } + } + catch { + Write-Log "Could not remove legacy scheduled task '$LegacyQueueTaskName': $($_.Exception.Message)" 'WARN' + } +} + +function Register-OrUpdateTasks { + Unregister-LegacyQueueTask + + try { + $existingDaemon = Get-ScheduledTask -TaskName $DaemonTaskName -ErrorAction SilentlyContinue + if ($existingDaemon) { + Write-Log "Stopping scheduled task '$DaemonTaskName' before update." + Stop-ScheduledTask -TaskName $DaemonTaskName -ErrorAction SilentlyContinue + Start-Sleep -Seconds 2 + } + } + catch { + Write-Log "Could not stop daemon task '$DaemonTaskName': $($_.Exception.Message)" 'WARN' + } + + $principal = New-ScheduledTaskPrincipal ` + -UserId 'SYSTEM' ` + -LogonType ServiceAccount ` + -RunLevel Highest + + Write-Log "Registering/updating scheduled task '$DaemonTaskName'." + $daemonArgs = "-NoProfile -ExecutionPolicy Bypass -File `"$LocalScriptPath`" -Mode Daemon" + $daemonAction = New-ScheduledTaskAction -Execute $PowerShellExe -Argument $daemonArgs + $daemonTrigger = New-ScheduledTaskTrigger -AtStartup + $daemonSettings = New-ScheduledTaskSettingsSet ` + -AllowStartIfOnBatteries ` + -DontStopIfGoingOnBatteries ` + -StartWhenAvailable ` + -MultipleInstances IgnoreNew ` + -ExecutionTimeLimit (New-TimeSpan -Seconds 0) ` + -RestartCount 3 ` + -RestartInterval (New-TimeSpan -Minutes 1) + + $daemonTask = New-ScheduledTask ` + -Action $daemonAction ` + -Trigger $daemonTrigger ` + -Principal $principal ` + -Settings $daemonSettings + + Register-ScheduledTask -TaskName $DaemonTaskName -InputObject $daemonTask -Force | Out-Null + + Write-Log "Registering/updating scheduled task '$UpgradeTaskName'." + $upgradeArgs = "-NoProfile -ExecutionPolicy Bypass -File `"$LocalScriptPath`" -Mode UpgradeAll" + $upgradeAction = New-ScheduledTaskAction -Execute $PowerShellExe -Argument $upgradeArgs + $upgradeTrigger = New-ScheduledTaskTrigger ` + -Once ` + -At ((Get-Date).AddMinutes(2)) ` + -RepetitionInterval (New-TimeSpan -Hours 2) ` + -RepetitionDuration (New-TimeSpan -Days 3650) + $upgradeSettings = New-ScheduledTaskSettingsSet ` + -AllowStartIfOnBatteries ` + -DontStopIfGoingOnBatteries ` + -StartWhenAvailable ` + -MultipleInstances IgnoreNew ` + -ExecutionTimeLimit (New-TimeSpan -Hours 2) + + $upgradeTask = New-ScheduledTask ` + -Action $upgradeAction ` + -Trigger $upgradeTrigger ` + -Principal $principal ` + -Settings $upgradeSettings + + Register-ScheduledTask -TaskName $UpgradeTaskName -InputObject $upgradeTask -Force | Out-Null + + try { + Start-ScheduledTask -TaskName $DaemonTaskName + } + catch { + Write-Log "Could not start daemon task '$DaemonTaskName': $($_.Exception.Message)" 'WARN' + } +} + +function Invoke-WingetInstall { + param( + [Parameter(Mandatory)][string]$WingetPath, + [Parameter(Mandatory)][string]$PackageId + ) + + $arguments = @( + 'install' + '--id', $PackageId + '--exact' + '--scope', 'machine' + '--silent' + '--accept-package-agreements' + '--accept-source-agreements' + '--disable-interactivity' + ) + + Write-Log "Executing: `"$WingetPath`" $($arguments -join ' ')" + $output = & $WingetPath @arguments 2>&1 | Out-String + $exitCode = $LASTEXITCODE + + if ($output) { + foreach ($line in ($output -split "`r?`n")) { + if ($line.Trim()) { + Write-Log "winget: $line" + } + } + } + + return $exitCode +} + +function Invoke-WingetUninstall { + param( + [Parameter(Mandatory)][string]$WingetPath, + [Parameter(Mandatory)][string]$PackageId + ) + + $arguments = @( + 'uninstall' + '--id', $PackageId + '--exact' + '--scope', 'machine' + '--silent' + '--accept-source-agreements' + '--disable-interactivity' + ) + + Write-Log "Executing: `"$WingetPath`" $($arguments -join ' ')" + $output = & $WingetPath @arguments 2>&1 | Out-String + $exitCode = $LASTEXITCODE + + if ($output) { + foreach ($line in ($output -split "`r?`n")) { + if ($line.Trim()) { + Write-Log "winget: $line" + } + } + } + + return $exitCode +} + +function Invoke-WingetUpgradeAll { + param([Parameter(Mandatory)][string]$WingetPath) + + $arguments = @( + 'upgrade' + '--all' + '--scope', 'machine' + '--silent' + '--accept-package-agreements' + '--accept-source-agreements' + '--disable-interactivity' + ) + + Write-Log "Executing 2-hour upgrade: `"$WingetPath`" $($arguments -join ' ')" + $output = & $WingetPath @arguments 2>&1 | Out-String + $exitCode = $LASTEXITCODE + + if ($output) { + foreach ($line in ($output -split "`r?`n")) { + if ($line.Trim()) { + Write-Log "winget upgrade: $line" + } + } + } + + return $exitCode +} + +function Update-InstalledPackagesSnapshot { + param([Parameter(Mandatory)][string]$WingetPath) + + Ensure-Directory -Path $BaseDir + + $tempRoot = if ($env:TEMP) { $env:TEMP } elseif ($env:TMP) { $env:TMP } else { $BaseDir } + $tempFile = Join-Path $tempRoot ("selfservice-winget-export-{0}.json" -f [Guid]::NewGuid().ToString('N')) + $snapshotTempFile = Join-Path $BaseDir ("Installed-Packages-{0}.json.tmp" -f [Guid]::NewGuid().ToString('N')) + + $arguments = @( + 'export' + '--output', $tempFile + '--accept-source-agreements' + '--disable-interactivity' + ) + + Write-Log 'Refreshing installed package snapshot.' + $output = & $WingetPath @arguments 2>&1 | Out-String + $exitCode = $LASTEXITCODE + + if ($output) { + foreach ($line in ($output -split "`r?`n")) { + if ($line.Trim()) { + Write-Log "winget export: $line" + } + } + } + + if ($exitCode -ne 0) { + Write-Log "winget export failed with code $exitCode; snapshot was not updated." 'WARN' + if (Test-Path -LiteralPath $tempFile) { + Remove-Item -LiteralPath $tempFile -Force -ErrorAction SilentlyContinue + } + return $false + } + + if (-not (Test-Path -LiteralPath $tempFile)) { + Write-Log 'winget export did not produce an output file; snapshot was not updated.' 'WARN' + return $false + } + + try { + $raw = Get-Content -LiteralPath $tempFile -Raw -Encoding UTF8 + $export = $raw | ConvertFrom-Json + + $packageIds = @() + foreach ($source in @($export.Sources)) { + foreach ($pkg in @($source.Packages)) { + if ($pkg.PackageIdentifier) { + $packageIds += [string]$pkg.PackageIdentifier + } + elseif ($pkg.PackageId) { + $packageIds += [string]$pkg.PackageId + } + } + } + + $packageIds = $packageIds | + Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | + ForEach-Object { $_.Trim() } | + Sort-Object -Unique + + $snapshot = [ordered]@{ + GeneratedAt = (Get-Date).ToString('o') + InstalledPackageIds = @($packageIds) + } + + $snapshot | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $snapshotTempFile -Encoding UTF8 + Move-Item -LiteralPath $snapshotTempFile -Destination $InstalledPackagesPath -Force + Write-Log "Installed package snapshot written to '$InstalledPackagesPath' (count=$(@($packageIds).Count))." + return $true + } + catch { + Write-Log "Failed to write installed package snapshot: $($_.Exception.Message)" 'WARN' + return $false + } + finally { + if (Test-Path -LiteralPath $tempFile) { + Remove-Item -LiteralPath $tempFile -Force -ErrorAction SilentlyContinue + } + if (Test-Path -LiteralPath $snapshotTempFile) { + Remove-Item -LiteralPath $snapshotTempFile -Force -ErrorAction SilentlyContinue + } + } +} + +function New-CatalogPipeSecurity { + $pipeSecurity = New-Object System.IO.Pipes.PipeSecurity + + $sidSystem = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-18') + $sidAdmins = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-544') + $sidUsers = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-545') + + $ruleSystem = New-Object System.IO.Pipes.PipeAccessRule( + $sidSystem, + [System.IO.Pipes.PipeAccessRights]::FullControl, + [System.Security.AccessControl.AccessControlType]::Allow + ) + $ruleAdmins = New-Object System.IO.Pipes.PipeAccessRule( + $sidAdmins, + [System.IO.Pipes.PipeAccessRights]::FullControl, + [System.Security.AccessControl.AccessControlType]::Allow + ) + $ruleUsers = New-Object System.IO.Pipes.PipeAccessRule( + $sidUsers, + [System.IO.Pipes.PipeAccessRights]::ReadWrite, + [System.Security.AccessControl.AccessControlType]::Allow + ) + + $null = $pipeSecurity.AddAccessRule($ruleSystem) + $null = $pipeSecurity.AddAccessRule($ruleAdmins) + $null = $pipeSecurity.AddAccessRule($ruleUsers) + + return $pipeSecurity +} + +function New-CatalogPipeServer { + $pipeSecurity = New-CatalogPipeSecurity + return New-Object System.IO.Pipes.NamedPipeServerStream -ArgumentList @( + $PipeName, + [System.IO.Pipes.PipeDirection]::InOut, + 1, + [System.IO.Pipes.PipeTransmissionMode]::Byte, + [System.IO.Pipes.PipeOptions]::None, + 4096, + 4096, + $pipeSecurity + ) +} + +function Get-PipeClientIdentity { + param([Parameter(Mandatory)][System.IO.Pipes.NamedPipeServerStream]$Pipe) + + $script:PipeClientIdentityName = $null + $script:PipeClientIdentitySid = $null + + try { + $Pipe.RunAsClient([System.IO.Pipes.PipeStreamImpersonationWorker]{ + $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent() + $script:PipeClientIdentityName = $identity.Name + if ($identity.User) { + $script:PipeClientIdentitySid = $identity.User.Value + } + }) + } + catch { + try { + $script:PipeClientIdentityName = $Pipe.GetImpersonationUserName() + } + catch { + } + } + + if ([string]::IsNullOrWhiteSpace($script:PipeClientIdentityName)) { + $script:PipeClientIdentityName = 'Unknown' + } + + return [pscustomobject]@{ + Name = $script:PipeClientIdentityName + Sid = $script:PipeClientIdentitySid + } +} + +function Invoke-CatalogDaemonCommand { + param( + [Parameter(Mandatory)]$Request, + [Parameter(Mandatory)]$ClientIdentity + ) + + if (-not $ClientIdentity -or [string]::IsNullOrWhiteSpace($ClientIdentity.Name) -or $ClientIdentity.Name -eq 'Unknown') { + throw 'Named pipe client could not be authenticated.' + } + + $command = $null + $commandProperty = $Request.PSObject.Properties['Command'] + $actionProperty = $Request.PSObject.Properties['Action'] + if ($commandProperty -and $commandProperty.Value) { + $command = [string]$commandProperty.Value + } + elseif ($actionProperty -and $actionProperty.Value) { + $command = [string]$actionProperty.Value + } + + if ([string]::IsNullOrWhiteSpace($command)) { + throw 'Missing command.' + } + + $command = $command.Trim().ToLowerInvariant() + + switch ($command) { + { $_ -in @('install','uninstall') } { + $appAliasProperty = $Request.PSObject.Properties['AppAlias'] + if (-not $appAliasProperty -or [string]::IsNullOrWhiteSpace([string]$appAliasProperty.Value)) { + throw 'Missing AppAlias.' + } + + $alias = ([string]$appAliasProperty.Value).Trim().ToLowerInvariant() + $packageId = Get-PackageIdByAlias -Alias $alias + if (-not $packageId) { + throw "Alias '$alias' is not in the allowlist." + } + + $actionText = if ($command -eq 'uninstall') { 'uninstall' } else { 'install' } + Write-Log "Authenticated request: action=$actionText alias='$alias' package='$packageId' user='$($ClientIdentity.Name)' sid='$($ClientIdentity.Sid)'" + + $wingetPath = Ensure-WingetAvailable + if (-not $wingetPath) { + throw 'winget is unavailable.' + } + + $result = Invoke-WithWingetLock -ScriptBlock { + if ($command -eq 'uninstall') { + $exitCode = Invoke-WingetUninstall -WingetPath $wingetPath -PackageId $packageId + } + else { + $exitCode = Invoke-WingetInstall -WingetPath $wingetPath -PackageId $packageId + } + + $snapshotUpdated = $false + if ($exitCode -eq 0) { + $snapshotUpdated = Update-InstalledPackagesSnapshot -WingetPath $wingetPath + } + + [pscustomobject]@{ + ExitCode = $exitCode + SnapshotUpdated = [bool]$snapshotUpdated + } + } + $result = @($result)[-1] + + if ($result.ExitCode -ne 0) { + throw "winget $actionText exited with code $($result.ExitCode) for package '$packageId'." + } + + $verb = if ($command -eq 'uninstall') { 'Deinstallation' } else { 'Installation' } + return [pscustomobject]@{ + Success = $true + Command = $command + AppAlias = $alias + PackageId = $packageId + RequestedBy = $ClientIdentity.Name + RequestedBySid = $ClientIdentity.Sid + ExitCode = $result.ExitCode + SnapshotUpdated = $result.SnapshotUpdated + Message = "$verb abgeschlossen: $alias" + } + } + + { $_ -in @('refreshstatus','getstatus') } { + Write-Log "Authenticated status refresh requested by user='$($ClientIdentity.Name)' sid='$($ClientIdentity.Sid)'" + $wingetPath = Ensure-WingetAvailable + if (-not $wingetPath) { + throw 'winget is unavailable.' + } + + $result = Invoke-WithWingetLock -ScriptBlock { + $snapshotUpdated = Update-InstalledPackagesSnapshot -WingetPath $wingetPath + [pscustomobject]@{ SnapshotUpdated = [bool]$snapshotUpdated } + } + $result = @($result)[-1] + + return [pscustomobject]@{ + Success = [bool]$result.SnapshotUpdated + Command = $command + RequestedBy = $ClientIdentity.Name + RequestedBySid = $ClientIdentity.Sid + SnapshotUpdated = [bool]$result.SnapshotUpdated + Message = 'Installationsdaten aktualisiert.' + } + } + + default { + throw "Unsupported command '$command'." + } + } +} + +function Start-CatalogDaemon { + Ensure-Directory -Path $BaseDir + Ensure-Directory -Path $LogDir + + Write-Log "Named pipe daemon starting on '\\.\pipe\$PipeName'." + + try { + $wingetPath = Ensure-WingetAvailable + if ($wingetPath) { + Invoke-WithWingetLock -ScriptBlock { + $null = Update-InstalledPackagesSnapshot -WingetPath $wingetPath + } + } + } + catch { + Write-Log "Initial installed package snapshot failed: $($_.Exception.Message)" 'WARN' + } + + while ($true) { + $pipe = $null + try { + $pipe = New-CatalogPipeServer + $pipe.WaitForConnection() + + $clientIdentity = Get-PipeClientIdentity -Pipe $pipe + $encoding = New-Object System.Text.UTF8Encoding($false) + $reader = New-Object System.IO.StreamReader($pipe, $encoding) + $writer = New-Object System.IO.StreamWriter($pipe, $encoding) + $writer.AutoFlush = $true + + $response = $null + try { + $line = $reader.ReadLine() + if ([string]::IsNullOrWhiteSpace($line)) { + throw 'Empty request.' + } + + $request = $line | ConvertFrom-Json + $response = Invoke-CatalogDaemonCommand -Request $request -ClientIdentity $clientIdentity + } + catch { + Write-Log "Named pipe request failed: $($_.Exception.Message)" 'ERROR' + $response = [pscustomobject]@{ + Success = $false + RequestedBy = $clientIdentity.Name + RequestedBySid = $clientIdentity.Sid + Message = $_.Exception.Message + } + } + + $writer.WriteLine(($response | ConvertTo-Json -Compress -Depth 6)) + } + catch { + Write-Log "Named pipe daemon error: $($_.Exception.Message)" 'ERROR' + Start-Sleep -Seconds 3 + } + finally { + if ($pipe) { + $pipe.Dispose() + } + } + } +} + +function Invoke-UpgradeAllMode { + Ensure-Directory -Path $BaseDir + Ensure-Directory -Path $LogDir + + $wingetPath = Ensure-WingetAvailable + if (-not $wingetPath) { + Write-Log 'Aborting upgrade because winget is unavailable.' 'ERROR' + return + } + + $result = Invoke-WithWingetLock -ScriptBlock { + $exitCode = Invoke-WingetUpgradeAll -WingetPath $wingetPath + $snapshotUpdated = Update-InstalledPackagesSnapshot -WingetPath $wingetPath + [pscustomobject]@{ + ExitCode = $exitCode + SnapshotUpdated = [bool]$snapshotUpdated + } + } + $result = @($result)[-1] + + if ($result.ExitCode -eq 0) { + Write-Log "2-hour winget upgrade completed successfully. SnapshotUpdated=$($result.SnapshotUpdated)." + } + else { + Write-Log "2-hour winget upgrade failed with code $($result.ExitCode). SnapshotUpdated=$($result.SnapshotUpdated)." 'WARN' + } +} + +function Install-Service { + Ensure-Directory -Path $BaseDir + Ensure-Directory -Path $LogDir + + Set-DirectoryAcl -Path $BaseDir -UsersCanModify:$false + Set-DirectoryAcl -Path $LogDir -UsersCanModify:$false + + foreach ($legacyDirName in @('Requests','Processed','Failed')) { + $legacyDirPath = Join-Path $BaseDir $legacyDirName + if (Test-Path -LiteralPath $legacyDirPath) { + Set-DirectoryAcl -Path $legacyDirPath -UsersCanModify:$false + } + } + + if (-not $PSCommandPath) { + throw 'PSCommandPath is empty; cannot determine the source script path.' + } + + Copy-Item -LiteralPath $PSCommandPath -Destination $LocalScriptPath -Force + Set-FileAclAdminsOnly -Path $LocalScriptPath + + New-UserRequestTool + New-CatalogGui + New-CatalogLauncher + New-Shortcut -ShortcutPath $DesktopShortcutPath + New-Shortcut -ShortcutPath $StartMenuShortcutPath + Register-OrUpdateTasks + + Write-Log 'Install/update completed successfully.' +} + +# ---------------------------- +# Entry point +# ---------------------------- +try { + switch ($Mode) { + 'Install' { Install-Service } + 'Daemon' { Start-CatalogDaemon } + 'UpgradeAll' { Invoke-UpgradeAllMode } + default { throw "Unsupported mode '$Mode'." } + } +} +catch { + try { + Write-Log "Fatal error in mode '$Mode': $($_.Exception.Message)" 'ERROR' + } + catch { + } + throw +}