Full Code of MightyMoud/sidekick for AI

main ffd3fb06d5ce cached
30 files
183.9 KB
59.3k tokens
97 symbols
1 requests
Download .txt
Repository: MightyMoud/sidekick
Branch: main
Commit: ffd3fb06d5ce
Files: 30
Total size: 183.9 KB

Directory structure:
gitextract_0fuar_rb/

├── .gitignore
├── .goreleaser.yaml
├── LICENSE
├── README.md
├── cmd/
│   ├── config/
│   │   └── config.go
│   ├── deploy/
│   │   └── deploy.go
│   ├── destroy.go
│   ├── initialize/
│   │   └── initialize.go
│   ├── launch/
│   │   └── launch.go
│   ├── preview/
│   │   ├── list/
│   │   │   └── list.go
│   │   ├── preview.go
│   │   └── remove/
│   │       └── remove.go
│   └── root.go
├── go.mod
├── go.sum
├── main.go
├── render/
│   ├── tui.go
│   ├── types.go
│   └── utils.go
├── scripts/
│   ├── destroy-droplets.py
│   └── make-droplet.py
└── utils/
    ├── auth.go
    ├── config.go
    ├── docker.go
    ├── scripts.go
    ├── spinner.go
    ├── stages.go
    ├── types.go
    ├── utils.go
    └── utils_test.go

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

================================================
FILE: .gitignore
================================================

dist/
.DS_Store


================================================
FILE: .goreleaser.yaml
================================================
# This is an example .goreleaser.yml file with some sensible defaults.
# Make sure to check the documentation at https://goreleaser.com

# The lines below are called `modelines`. See `:help modeline`
# Feel free to remove those if you don't want/need to use them.
# yaml-language-server: $schema=https://goreleaser.com/static/schema.json
# vim: set ts=2 sw=2 tw=0 fo=cnqoj

version: 2

before:
  hooks:
    # You may remove this if you don't use go modules.
    - go mod tidy

builds:
  - env:
      - CGO_ENABLED=0
    ldflags:
      - "-X 'github.com/mightymoud/sidekick/cmd.version={{.Tag}}'"
    goos:
      - linux
      - windows
      - darwin

archives:
  - format: tar.gz
    # this name template makes the OS and Arch compatible with the results of `uname`.
    name_template: >-
      {{ .ProjectName }}_
      {{- title .Os }}_
      {{- if eq .Arch "amd64" }}x86_64
      {{- else if eq .Arch "386" }}i386
      {{- else }}{{ .Arch }}{{ end }}
      {{- if .Arm }}v{{ .Arm }}{{ end }}
    # use zip for windows archives
    format_overrides:
      - goos: windows
        format: zip

changelog:
  sort: asc
  filters:
    exclude:
      - "^docs:"
      - "^test:"
      - "^chore:"

release:
    draft: true



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

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

                            Preamble

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

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

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

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

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

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

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

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

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

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

                       TERMS AND CONDITIONS

  0. Definitions.

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

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

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

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

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

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

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

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

  1. Source Code.

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

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

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

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

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

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

  2. Basic Permissions.

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

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

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

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

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

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

  4. Conveying Verbatim Copies.

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

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

  5. Conveying Modified Source Versions.

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

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

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

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

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

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

  6. Conveying Non-Source Forms.

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

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

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

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

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

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

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

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

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

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

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

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

  7. Additional Terms.

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

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

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

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

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

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

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

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

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

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

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

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

  8. Termination.

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

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

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

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

  9. Acceptance Not Required for Having Copies.

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

  10. Automatic Licensing of Downstream Recipients.

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

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

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

  11. Patents.

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

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

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

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

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

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

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

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

  12. No Surrender of Others' Freedom.

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

  13. Use with the GNU Affero General Public License.

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

  14. Revised Versions of this License.

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

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

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

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

  15. Disclaimer of Warranty.

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

  16. Limitation of Liability.

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

  17. Interpretation of Sections 15 and 16.

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

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

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

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

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

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

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

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

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

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

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

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

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

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


================================================
FILE: README.md
================================================
<div align="center">
  <div>
    <img width="110px" src="https://emoji.aranja.com/static/emoji-data/img-apple-160/1f91c-1f3fb.png">
    <img width="110px" src="https://emoji.aranja.com/static/emoji-data/img-apple-160/1f91b-1f3fb.png">
  </div>

Bare metal to production ready in mins; imagine fly.io on your VPS

  <div>
    <img width="600px" src="/demo/imgs/hero.png">
  </div>

![GitHub](https://img.shields.io/github/license/mightymoud/sidekick)
![GitHub go.mod Go version](https://img.shields.io/github/go-mod/go-version/mightymoud/sidekick)
![GitHub tag (latest SemVer)](https://img.shields.io/github/v/tag/mightymoud/sidekick)

</div>

## Features

- 👍 One command VPS setup (docker, traefik, sops, age)
- 💻 deploy any application from a dockerfile
- ✊ Zero downtime deployment
- 🌏 High availability and load balancing
- 🔒 Zero config SSL Certs
- ✅ Connect domains or use sslip.io out of the box
- 🔥 Built in integration with SOPS
- 🛸 Escape the vendorlock forever

## Motivation

I'm tired of the complexity involved in hosting my side projects. While some platforms, like Fly.io, stand out in the crowded field of Heroku replacements, I believe a simple VPS can be just as effective. That's why I created Sidekick: to make hosting side projects as straightforward, affordable, and production-ready as possible. You'll be surprised how much traffic a $8/month instance on DigitalOcean can handle.

## Installation

Using brew:

```bash
brew install sidekick
```

NOTE: Sidekick uses `brew` later on to handle installing `sops` on your local. So `brew` is a requirement at this point. Sidekick will throw an error if `brew` is not found. You can install `brew` from [here](https://brew.sh/).

## Usage

Sidekick helps you along all the steps of deployment on your VPS. From basic setup to zero downtime deploys, we got you! ✊

First you need a VPS with Ubuntu LTS. I recommend DigitalOcean. Hetzner also gets very good reviews. You can host your own silicon too. As long as you have a public IP address you can use Sidekick.

Just make sure the following is true:

- VPS running Ubuntu - LTS recommended
- SSH Key available on your machine to login to VPS.

That's it!

### VPS Setup

  <div align="center" >
    <img width="600px" src="/demo/imgs/init.png">
  </div>

First you need to setup your VPS. To do this you need to run:

```bash
sidekick init
```

Then you need to enter the following:

- IP Address of your VPS
- An email address to use for setting up SSL certs

After that Sidekick will setup many things on your VPS - Usually takes around 2 mins.
If you run this command once more and enter a different IP Address, Sidekick will warn you that you are overriding the current config with a prompt.

You can use flags instead. Read more [in the docs](https://www.sidekickdeploy.com/docs/command/init/).

<details>
  <summary>What does Sidekick do when I run this command?</summary>
  
* Login with `root` user
* Make a new user `sidekick` and grant sudo access
* Logout from `root` and login with `sidekick`
* Disable login with `root` user - security best practice
* Update and upgrade your Ubuntu system
* Install `sops` and copy over the public key to your sidekick config file
* Use `age` to make secret and public keys to use later for encrypting env file.
* Send public key back to host machine to be used later for encryption
* Install Docker
* Add user sidekick to docker group
* Setup Traefik and SSL certs on your VPS
</details>

<details>
  <summary>Which SSH key will Sidekick use to login?</summary>

Sidekick will look up the default keys in your default .ssh directory in the following order:

- id_rsa.pub
- id_ecdsa.pub
- id_ed25519.pub

Sidekick will also get all keys from the `ssh-agent` and try them as well. If you want to use a custom key and not a default one, you would need to add the to your agent first by running `ssh-add KEY_FILE`

</details>

Read more details about flags and other options for this command [on the docs](https://www.sidekickdeploy.com/docs/command/init/)

### Launch a new application

  <div align="center" >
    <img width="600px" src="/demo/imgs/launch.png">
  </div>

In your application folder, make sure you have a working `Dockerfile` that you can build and run. Also make sure you know at which port your app is expecting to receive traffic.

Then run:

```bash
sidekick launch
```

Then you need to enter the following:

- Url friendly name of your app - if you opt to use `sslip.io` domain for testing this would be your subdomain
- HTTP exposed port for your app to get requests - Sidekick will scan your docker file to try to extract this number and default it.
- Domain at which you want this application to be reachable - If you choose your own domain make sure to point the domain to your VPS IP address; otherwise we default to `sslip.io` domain so you can play around.
- If you have any `env` file with secrets in it. Sidekick will attempt to find `.env` file in the root of your folder. Sidekick will use `sops` to encrypt your env file and inject the values securely at run time.

Should take around 2 more mins to be able to visit your application live on the web if all goes well.

<details>
  <summary>What does Sidekick do when I run this command</summary>
  
* Build your docker image locally for linux
* Move the docker image to your VPS directly
* Encrypt your env file, if available and push it to your VPS
* Use sops to decrypt your env file and start and env with the values injected
* Spin up your docker image using docker compose and route traffic to it using Traefik on the specified port
</details>

### Deploy a new version

  <div align="center" >
    <img width="600px" src="/demo/imgs/deploy.png">
  </div>
With your application deployed, it's super simple to deploy a new version.

At any point any time you need to only run:

```bash
sidekick deploy
```

That's all. It won't take long, we use cache from earlier docker images, your latest version should be up soon.
Sidekick will deploy the new version without any downtime - you can see more in the source code.
This command will also do a couple of things behind the scenes. You can check that below

<details>
  <summary>What does Sidekick do when I run this command</summary>
  
* Build your docker image locally for linux
* Compare your latest env file checksum for changes from last time you deployed your application.
* If your env file has changed, sidekick will re-encrypt it and replace the encrypted.env file on your server.
* Deploy the new version with zero downtime deploys so you don't miss any traffic. 
</details>

### Deploy a preview environment/app

  <div align="center" >
    <img width="600px" src="/demo/imgs/preview.png">
  </div>
Sidekick also allows you to deploy preview apps at any point from your application. Preview apps are attached to your commit hash and require a clean git tree before you can initiate them. 
Once you have a clean git tree, you can run the following command to deploy a preview app:

```bash
sidekick deploy preview
```

<details>
  <summary>What does Sidekick do when I run this command</summary>
  
* Build your docker image locally for linux
* Tag the new image with the short checksum of your git commit
* Encrypt your env file, if available and push it to your VPS
* Add a new folder inside your app folder called "preview" where Sidekick will store and manage all your preview deployments
* Deploy a new version of your app reachable on a short hash based subdomain
</details>

## Inspiration

- https://fly.io/
- https://kamal-deploy.org/

## Vision

Simple CLI tool that can help you:

- Setup your VPS
- Deploy all your side projects on a single VPS
- Load balance multiple container per project
- Deploy new versions with Zero downtime
- Deploy preview environments with ease
- Manage env secrets in a secure way
- Connect any number of domains and subdomains to your projects with ease

## Remove sidekick

You can easily remove sidekick if you hate it.

```bash
brew uninstall sidekick
```

---

## Roadmap

I still have a couple more feature I want to add here. Also considering some of those to be on a paid version.

- ✅ Preview env deployments
- A way to deploy more complicated projects defined in docker compose file
- Better zero downtime deploys with watchtower
- Firewall setup
- Managing multiple VPSs
- Easy way to deploy databases with one command
- TUI for monitoring your VPS
- Streaming down compose logs - ala `fly logs`
- Auto deploy on image push - to work with CICD better
- Git hooks setup for managing migrations and other concerns


================================================
FILE: cmd/config/config.go
================================================
/*
Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>

Licensed under the GNU GPL License, Version 3.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-3.0.en.html

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package config

import (
	"fmt"
	"os"

	"github.com/mightymoud/sidekick/utils"
	"github.com/pterm/pterm"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"gopkg.in/yaml.v3"
)

var ConfigCmd = &cobra.Command{
	Use:   "config",
	Short: "Subcommands for modifying sidekick config",
}

var currentContextCmd = &cobra.Command{
	Use:   "current",
	Short: "Get the current context from sidekick config",
	Run: func(cmd *cobra.Command, args []string) {
		config, err := utils.GetSidekickConfigFromCmdContext(cmd)
		if err != nil {
			pterm.Fatal.Println(err)
		}
		fmt.Println(config.CurrentContext)
	},
}

var useContextCmd = &cobra.Command{
	Use:   "use [context-name]",
	Short: "Switch the current context in sidekick config",
	Args:  cobra.ExactArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		config, err := utils.GetSidekickConfigFromCmdContext(cmd)
		if err != nil {
			pterm.Fatal.Println(err)
		}

		contextName := args[0]
		config.CurrentContext = contextName
		config.Save(viper.GetString("config"))
	},
}

var migrateCmd = &cobra.Command{
	Use:   "migrate",
	Short: "Migrate the old sidekick config to the new config",
	Run: func(cmd *cobra.Command, args []string) {
		var serverConfig utils.SidekickServer
		content, err := os.ReadFile(viper.GetString("config"))
		if err != nil {
			pterm.Fatal.Println(err)
		}
		err = yaml.Unmarshal(content, &serverConfig)
		if err != nil {
			pterm.Fatal.Println(err)
		}

		serverConfig.Name = "default"
		defaultContext := utils.SidekickContext{
			Name:   "default",
			Server: "default",
		}
		newConfig := utils.SidekickConfig{
			Version:        "1",
			Servers:        []utils.SidekickServer{serverConfig},
			Contexts:       []utils.SidekickContext{defaultContext},
			CurrentContext: defaultContext.Name,
		}
		err = newConfig.Print()
		if err != nil {
			pterm.Fatal.Println(err)
		}
	},
}

func init() {
	ConfigCmd.AddCommand(currentContextCmd)
	ConfigCmd.AddCommand(useContextCmd)
	ConfigCmd.AddCommand(migrateCmd)
}


================================================
FILE: cmd/deploy/deploy.go
================================================
/*
Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>

Licensed under the GNU GPL License, Version 3.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-3.0.en.html

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package deploy

import (
	"crypto/md5"
	"fmt"
	"net"
	"os"
	"os/exec"
	"slices"
	"strconv"
	"strings"
	"time"

	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/log"
	teaLog "github.com/charmbracelet/log"
	"github.com/mightymoud/sidekick/render"
	"github.com/mightymoud/sidekick/utils"
	"github.com/pterm/pterm"
	"github.com/spf13/cobra"
	"golang.org/x/crypto/ssh"
	"gopkg.in/yaml.v3"
)

func prelude(config *utils.SidekickConfig) (utils.SidekickAppConfig, utils.SidekickServer) {
	if !utils.FileExists("./sidekick.yml") {
		pterm.Error.Println(`Sidekick config not found in current directory Run sidekick launch`)
		os.Exit(1)
	}

	appConfig, loadError := utils.LoadAppConfig()
	if loadError != nil {
		panic(loadError)
	}

	// Older version of app config does not have server name
	// We will try to match the first server with IP matching the url
	if appConfig.Server == "" {
		render.GetLogger(teaLog.Options{Prefix: "Backward Compat"}).Info("An older version of sidekick.yml is found. Attempting to match a server from url...")
		ips, err := net.LookupIP(appConfig.Url)
		if err != nil {
			render.GetLogger(teaLog.Options{Prefix: "Backward Compat"}).Fatal(err)
		}
		for _, server := range config.Servers {
			if slices.ContainsFunc(ips, func(ip net.IP) bool {
				return ip.String() == server.Address
			}) {
				appConfig.Server = server.Name
				render.GetLogger(teaLog.Options{Prefix: "Backward Compat"}).Info("Found server", "name", server.Name, "IP", server.Address)
				break
			}
		}
	}

	if appConfig.Server == "" {
		render.GetLogger(teaLog.Options{Prefix: "Backward Compat"}).Fatal("Unable to find a server that this app was deployed.")
	}

	server, err := config.FindServer(appConfig.Server)
	if err != nil {
		render.GetLogger(teaLog.Options{Prefix: "Sidekick Config"}).Fatal(err)
	}

	if server.SecretKey == "" {
		render.GetLogger(teaLog.Options{Prefix: "Backward Compat"}).Error("Recent changes to how Sidekick handles secrets prevents you from launcing a new application.")
		render.GetLogger(teaLog.Options{Prefix: "Backward Compat"}).Info("To fix this, run `Sidekick init` with the same server address you have now.")
		render.GetLogger(teaLog.Options{Prefix: "Backward Compat"}).Info("Learn more at www.sidekickdeploy.com/docs/design/encryption")
		os.Exit(1)
	}

	return appConfig, server
}

func stage1Login(server *utils.SidekickServer) (*ssh.Client, error) {
	sshClient, err := utils.Login(server.Address, "sidekick")
	return sshClient, err
}

func stage2EnvFile(appConfig utils.SidekickAppConfig, p *tea.Program, server *utils.SidekickServer) (bool, string, error) {
	defer os.Remove("encrypted.env")
	envFileChanged := false
	currentEnvFileHash := ""
	if appConfig.Env.File != "" {
		envFileContent, envFileErr := os.ReadFile(fmt.Sprintf("./%s", appConfig.Env.File))
		if envFileErr != nil {
			return false, "", fmt.Errorf("failed to read environment file: %w", envFileErr)
		}
		currentEnvFileHash = fmt.Sprintf("%x", md5.Sum(envFileContent))
		envFileChanged = appConfig.Env.Hash != currentEnvFileHash
		if envFileChanged {
			// encrypt new env file
			envCmd := exec.Command("sh", "-s", "-", server.PublicKey, fmt.Sprintf("./%s", appConfig.Env.File))
			envCmd.Stdin = strings.NewReader(utils.EnvEncryptionScript)
			envCmdErrPipe, _ := envCmd.StderrPipe()
			go render.SendLogsToTUI(envCmdErrPipe, p)
			if envCmdErr := envCmd.Run(); envCmdErr != nil {
				return false, "", fmt.Errorf("failed to encrypt environment file: %w", envCmdErr)
			}
			encryptSyncCmd := exec.Command("rsync", "-v", "encrypted.env", fmt.Sprintf("%s@%s:%s", "sidekick", server.Address, fmt.Sprintf("./%s", appConfig.Name)))
			encryptSyncCmdErrPipe, _ := encryptSyncCmd.StderrPipe()
			go render.SendLogsToTUI(encryptSyncCmdErrPipe, p)
			if encryptSyncCmdErr := encryptSyncCmd.Run(); encryptSyncCmdErr != nil {
				return false, "", fmt.Errorf("failed to sync encrypted environment file to server: %w", encryptSyncCmdErr)
			}
		}
	}
	return envFileChanged, currentEnvFileHash, nil
}

func stage3BuildDockerImage(appConfig utils.SidekickAppConfig, p *tea.Program, server *utils.SidekickServer) error {
	cwd, _ := os.Getwd()
	dockerPlatformId := server.PlatformId
	dockerBuildCmd := exec.Command("docker", "build", "--tag", appConfig.Name, "--progress=plain", fmt.Sprintf("--platform=%s", dockerPlatformId), cwd)
	dockerBuildCmdErrPipe, _ := dockerBuildCmd.StderrPipe()
	go render.SendLogsToTUI(dockerBuildCmdErrPipe, p)

	if dockerBuildErr := dockerBuildCmd.Run(); dockerBuildErr != nil {
		return fmt.Errorf("failed to build Docker image: %w", dockerBuildErr)
	}
	return nil
}

func stage4SaveDockerImage(appConfig utils.SidekickAppConfig, p *tea.Program) error {
	imgFileName := fmt.Sprintf("%s-latest.tar", appConfig.Name)
	imgSaveCmd := exec.Command("docker", "save", "-o", imgFileName, appConfig.Name)
	imgSaveCmdErrPipe, _ := imgSaveCmd.StderrPipe()
	go render.SendLogsToTUI(imgSaveCmdErrPipe, p)

	if imgSaveCmdErr := imgSaveCmd.Run(); imgSaveCmdErr != nil {
		return fmt.Errorf("failed to save Docker image: %w", imgSaveCmdErr)
	}
	return nil
}

func stage5MoveDockerImage(appConfig utils.SidekickAppConfig, p *tea.Program, server *utils.SidekickServer) error {
	imgFileName := fmt.Sprintf("%s-latest.tar", appConfig.Name)
	remoteDist := fmt.Sprintf("%s@%s:./%s", "sidekick", server.Address, appConfig.Name)
	imgMoveCmd := exec.Command("scp", "-C", imgFileName, remoteDist)
	imgMoveCmdErrorPipe, _ := imgMoveCmd.StderrPipe()
	go render.SendLogsToTUI(imgMoveCmdErrorPipe, p)

	if imgMovCmdErr := imgMoveCmd.Run(); imgMovCmdErr != nil {
		return fmt.Errorf("failed to move Docker image to server: %w", imgMovCmdErr)
	}
	os.Remove(imgFileName)
	return nil
}

func stage6Deploy(sshClient *ssh.Client, appConfig utils.SidekickAppConfig, envFileChanged bool, currentEnvFileHash string, p *tea.Program, server *utils.SidekickServer) error {
	dockerLoadOutChan, _, sessionErr := utils.RunCommand(sshClient, fmt.Sprintf("cd %s && docker load -i %s-latest.tar", appConfig.Name, appConfig.Name))
	if sessionErr != nil {
		return fmt.Errorf("failed to load docker image on server: %w", sessionErr)
	}

	go func() {
		p.Send(render.LogMsg{LogLine: <-dockerLoadOutChan + "\n"})
		time.Sleep(time.Millisecond * 100)
	}()

	replacer := strings.NewReplacer(
		"$service_name", appConfig.Name,
		"$app_port", fmt.Sprint(appConfig.Port),
		"$has_env", appConfig.Env.File,
	)

	deployScript := replacer.Replace(utils.DeployAppScript)
	utils.RunCommandWithTUIHook(sshClient, deployScript, p, utils.EnvVar{"SOPS_AGE_KEY": server.SecretKey})
	time.Sleep(time.Second * 2)

	cleanOutChan, _, sessionErr := utils.RunCommand(sshClient, fmt.Sprintf("cd %s && rm %s", appConfig.Name, fmt.Sprintf("%s-latest.tar", appConfig.Name)))
	if sessionErr != nil {
		return fmt.Errorf("failed to clean up image file on server: %w", sessionErr)
	}
	go func() {
		p.Send(render.LogMsg{LogLine: <-cleanOutChan + "\n"})
		time.Sleep(time.Millisecond * 100)
	}()

	latestVersion := strings.Split(appConfig.Version, "")[1]
	latestVersionInt, _ := strconv.ParseInt(latestVersion, 0, 64)
	appConfig.Version = fmt.Sprintf("V%d", latestVersionInt+1)
	// env file changed ? -> update hash
	if envFileChanged {
		appConfig.Env.Hash = currentEnvFileHash
	}
	ymlData, _ := yaml.Marshal(&appConfig)
	os.WriteFile("./sidekick.yml", ymlData, 0644)

	return nil
}

var DeployCmd = &cobra.Command{
	Use:   "deploy",
	Short: "Deploy a new version of your application to your VPS using Sidekick",
	Long: `This command deploys a new version of your application to your VPS.
It assumes that your VPS is already configured and that your application is ready for deployment`,
	Run: func(cmd *cobra.Command, args []string) {
		start := time.Now()

		config, err := utils.GetSidekickConfigFromCmdContext(cmd)
		if err != nil {
			render.GetLogger(log.Options{Prefix: "Sidekick Config"}).Fatalf("%s", err)
		}
		appConfig, sidekickServer := prelude(config)

		cmdStages := []render.Stage{
			render.MakeStage("Validating connection with VPS", "VPS is reachable", false),
			render.MakeStage("Updating secrets if needed", "Env file check complete", false),
			render.MakeStage("Building latest docker image of your app", "Latest docker image built", true),
			render.MakeStage("Saving docker image locally", "Image saved successfully", false),
			render.MakeStage("Moving image to your server", "Image moved and loaded successfully", false),
			render.MakeStage("Deploying a new version of your application", "Deployed new version successfully", true),
		}
		p := tea.NewProgram(render.TuiModel{
			Stages:      cmdStages,
			BannerMsg:   fmt.Sprintf("Deploying a new env of your app to server %s (%s) 😎", sidekickServer.Name, sidekickServer.Address),
			ActiveIndex: 0,
			Quitting:    false,
			AllDone:     false,
		})

		go func() {
			sshClient, err := stage1Login(&sidekickServer)
			if err != nil {
				p.Send(render.ErrorMsg{ErrorStr: "Failed to connect to VPS: " + err.Error()})
				return
			}
			p.Send(render.NextStageMsg{})

			envFileChanged, currentEnvFileHash, err := stage2EnvFile(appConfig, p, &sidekickServer)
			if err != nil {
				p.Send(render.ErrorMsg{ErrorStr: err.Error()})
				return
			}
			p.Send(render.NextStageMsg{})

			if err := stage3BuildDockerImage(appConfig, p, &sidekickServer); err != nil {
				p.Send(render.ErrorMsg{ErrorStr: err.Error()})
				return
			}
			time.Sleep(time.Millisecond * 100)
			p.Send(render.NextStageMsg{})

			if err := stage4SaveDockerImage(appConfig, p); err != nil {
				p.Send(render.ErrorMsg{ErrorStr: err.Error()})
				return
			}
			time.Sleep(time.Millisecond * 200)
			p.Send(render.NextStageMsg{})

			if err := stage5MoveDockerImage(appConfig, p, &sidekickServer); err != nil {
				p.Send(render.ErrorMsg{ErrorStr: err.Error()})
				return
			}
			time.Sleep(time.Millisecond * 200)
			p.Send(render.NextStageMsg{})

			if err := stage6Deploy(sshClient, appConfig, envFileChanged, currentEnvFileHash, p, &sidekickServer); err != nil {
				p.Send(render.ErrorMsg{ErrorStr: err.Error()})
				return
			}

			time.Sleep(time.Millisecond * 500)
			p.Send(render.AllDoneMsg{Message: "🚀 Deployed successfully in " + time.Since(start).Round(time.Second).String() + ".\n" + "😎 View your app at https://" + appConfig.Url})
		}()

		if _, err := p.Run(); err != nil {
			fmt.Println("Error running program:", err)
			os.Exit(1)
		}
	},
}


================================================
FILE: cmd/destroy.go
================================================
/*
Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>

Licensed under the GNU GPL License, Version 3.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-3.0.en.html

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd

import (
	"fmt"

	"github.com/spf13/cobra"
)

// destroyCmd represents the destroy command
var destroyCmd = &cobra.Command{
	Use:   "destroy",
	Short: "A command to destroy your app on the VPS and remove the container and the images",
	Long:  `This command is destructive and will remove everything related to your application from the VPS. Please use it with care`,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("destroy called")
	},
}

func init() {
	rootCmd.AddCommand(destroyCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// destroyCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// destroyCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}


================================================
FILE: cmd/initialize/initialize.go
================================================
/*
Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>

Licensed under the GNU GPL License, Version 3.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-3.0.en.html

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package initialize

import (
	"fmt"
	"log"
	"os"
	"os/exec"
	"strings"
	"time"

	tea "github.com/charmbracelet/bubbletea"
	"github.com/docker/docker/pkg/namesgenerator"
	"github.com/mightymoud/sidekick/render"
	"github.com/mightymoud/sidekick/utils"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"golang.org/x/crypto/ssh"
)

func stage1LocalReqs() error {
	if _, err := exec.LookPath("sops"); err != nil {
		cmd := exec.Command("brew", "install", "sops")
		if err := cmd.Run(); err != nil {
			return fmt.Errorf("failed to install sops: %w", err)
		}
	}
	if _, err := exec.LookPath("age"); err != nil {
		cmd := exec.Command("brew", "install", "age")
		if err := cmd.Run(); err != nil {
			return fmt.Errorf("failed to install age: %w", err)
		}
	}
	return nil
}

func stage2Login(server string) (*ssh.Client, string, error) {
	users := []string{"root", "sidekick"}
	for _, user := range users {
		client, err := utils.Login(server, user)
		if err == nil {
			return client, user, nil
		}
	}
	return nil, "", fmt.Errorf("unable to establish SSH connection")
}

func stage3UserSetup(client *ssh.Client, loggedInUser string) error {
	hasSidekickUser := true
	outChan, _, err := utils.RunCommand(client, "id -u sidekick")
	if err != nil {
		hasSidekickUser = false
	} else {
		output := <-outChan
		if output == "" {
			hasSidekickUser = false
		}
	}

	if !hasSidekickUser && loggedInUser == "root" {
		if err := utils.RunStage(client, utils.UsersetupStage); err != nil {
			return err
		}
	}
	return nil
}

func stage4VPSSetup(client *ssh.Client, p *tea.Program, server *utils.SidekickServer) error {
	// get the linux distro
	outChan, _, _ := utils.RunCommand(client, "grep '^ID=' /etc/os-release | awk -F'=' '{print $2}'")
	linuxDistro := <-outChan
	server.Distro = linuxDistro

	// get docker platform id
	cmdOutChan, _, _ := utils.RunCommand(client, "uname -m")
	arch := <-cmdOutChan
	if arch == "x86_64" {
		server.PlatformId = "linux/amd64"
	}
	if arch == "aarch64" {
		server.PlatformId = "linux/arm64"
	}

	if err := utils.RunCommandsWithTUIHook(client, utils.SetupStage.Commands, p); err != nil {
		return err
	}

	if server.PublicKey == "" || server.SecretKey == "" {
		cmd := exec.Command("age-keygen")
		output, err := cmd.Output()
		if err != nil {
			return err
		}
		outStr := string(output)
		lines := strings.Split(outStr, "\n")
		if len(lines) >= 3 {
			server.SecretKey = lines[2]
			parts := strings.Split(lines[1], ":")
			if len(parts) > 1 {
				server.PublicKey = strings.ReplaceAll(parts[1], " ", "")
			}
		}
	}
	return nil
}

func stage5Docker(client *ssh.Client, p *tea.Program) error {
	dockerReady := false
	outChan, _, err := utils.RunCommand(client, `command -v docker &> /dev/null && command -v docker compose &> /dev/null && echo "1" || echo "0"`)
	if err == nil {
		output := <-outChan
		if output == "1" {
			dockerReady = true
		}
	}

	if !dockerReady {
		if err := utils.RunCommandsWithTUIHook(client, utils.DockerStage.Commands, p); err != nil {
			return err
		}
	}
	return nil
}

func stage6Traefik(client *ssh.Client, email string, p *tea.Program) error {
	traefikSetup := false
	outChan, _, err := utils.RunCommand(client, `[ -d "traefik" ] && echo "1" || echo "0"`)
	if err == nil {
		output := <-outChan
		if output == "1" {
			traefikSetup = true
		}
	}

	if !traefikSetup {
		traefikStage := utils.GetTraefikStage(email)
		if err := utils.RunCommandsWithTUIHook(client, traefikStage.Commands, p); err != nil {
			return err
		}
	}
	return nil
}

var InitCmd = &cobra.Command{
	Use:   "init",
	Short: "Init sidekick CLI and configure your VPS to host your apps",
	Long: `This command will run you through the setup steps to get sidekick loaded on your VPS.
		You wil need to provide your VPS IPv4 address and a registry to host your docker images.
		`,
	Run: func(cmd *cobra.Command, args []string) {
		start := time.Now()

		config, err := utils.GetSidekickConfigFromCmdContext(cmd)
		if err != nil {
			log.Fatalf("%s", err)
		}

		skipPromptsFlag, _ := cmd.Flags().GetBool("yes")
		server, _ := cmd.Flags().GetString("server")
		certEmail, _ := cmd.Flags().GetString("email")
		name, _ := cmd.Flags().GetString("name")

		if name == "" {
			randomName := namesgenerator.GetRandomName(0)
			name = render.GenerateTextQuestion("Please enter a name for your VPS", randomName, "")
		}

		if server == "" {
			server = render.GenerateTextQuestion("Please enter the IPv4 Address of your VPS", "", "")
			if !utils.IsValidIPAddress(server) {
				log.Fatalf("You entered an incorrect IP Address - %s", server)
			}
		}

		if certEmail == "" {
			certEmail = render.GenerateTextQuestion("Please enter an email for use with TLS certs", "", "")
			if certEmail == "" {
				log.Fatalf("An email is needed before you proceed")
			}
		}

		sidekickServer, err := config.FindServer(name)
		if err != nil {
			sidekickServer = utils.SidekickServer{
				Name:      name,
				Address:   server,
				CertEmail: certEmail,
			}
		}

		if sidekickServer.Name == name && sidekickServer.Address != server && sidekickServer.PublicKey != "" && !skipPromptsFlag {
			confirm := render.GenerateTextQuestion(fmt.Sprintf("The server '%s' was previously setup with Sidekick using a different address. Would you like to overwrite the settings? (y/n)", sidekickServer.Name), "n", "")
			if strings.ToLower(confirm) != "y" {
				fmt.Println("\nYou can use a different server name to complete the setup")
				os.Exit(0)
			}
		}

		sidekickServer.Address = server
		sidekickServer.CertEmail = certEmail

		cmdStages := []render.Stage{
			render.MakeStage("Setting up your local env", "Installed local requirements successfully", false),
			render.MakeStage("Logging in to VPS", "Logged in successfully", false),
			render.MakeStage("Adding user Sidekick", "User Sidekick added successfully", false),
			render.MakeStage("Setting up VPS", "VPS setup successfully", true),
			render.MakeStage("Setting up Docker", "Docker setup successfully", true),
			render.MakeStage("Setting up Traefik", "Traefik setup successfully", true),
		}

		p := tea.NewProgram(render.TuiModel{
			Stages:      cmdStages,
			BannerMsg:   "Sidekick booting up! 🚀",
			ActiveIndex: 0,
			Quitting:    false,
			AllDone:     false,
		})

		utils.Login(server, "root")

		go func() {
			if err := stage1LocalReqs(); err != nil {
				p.Send(render.ErrorMsg{ErrorStr: fmt.Sprintf("Local requirements check failed: %s", err)})
				return
			}
			time.Sleep(time.Millisecond * 100)
			p.Send(render.NextStageMsg{})

			sshClient, loggedInUser, err := stage2Login(server)
			if err != nil {
				p.Send(render.ErrorMsg{ErrorStr: fmt.Sprintf("Login failed: %s", err)})
				return
			}
			time.Sleep(time.Millisecond * 100)
			p.Send(render.NextStageMsg{})

			if err := stage3UserSetup(sshClient, loggedInUser); err != nil {
				p.Send(render.ErrorMsg{ErrorStr: fmt.Sprintf("User setup failed: %s", err)})
				return
			}

			sidekickClient, err := utils.Login(server, "sidekick")
			if err != nil {
				p.Send(render.ErrorMsg{ErrorStr: fmt.Sprintf("Failed to login as sidekick: %s", err)})
				return
			}
			time.Sleep(time.Millisecond * 100)
			p.Send(render.NextStageMsg{})

			if err := stage4VPSSetup(sidekickClient, p, &sidekickServer); err != nil {
				p.Send(render.ErrorMsg{ErrorStr: fmt.Sprintf("VPS setup failed: %s", err)})
				return
			}
			time.Sleep(time.Millisecond * 100)
			p.Send(render.NextStageMsg{})

			if err := stage5Docker(sidekickClient, p); err != nil {
				p.Send(render.ErrorMsg{ErrorStr: fmt.Sprintf("Docker setup failed: %s", err)})
				return
			}
			time.Sleep(time.Millisecond * 100)
			p.Send(render.NextStageMsg{})

			if err := stage6Traefik(sidekickClient, certEmail, p); err != nil {
				p.Send(render.ErrorMsg{ErrorStr: fmt.Sprintf("Traefik setup failed: %s", err)})
				return
			}

			config.AddOrReplaceServer(sidekickServer)
			newContext := utils.SidekickContext{Name: sidekickServer.Name, Server: sidekickServer.Name}
			config.AddOrReplaceContext(newContext)
			config.CurrentContext = newContext.Name

			if err := config.Save(viper.GetString("config")); err != nil {
				p.Send(render.ErrorMsg{ErrorStr: fmt.Sprintf("Failed to write config: %s", err)})
				return
			}

			p.Send(render.AllDoneMsg{Message: "VPS Setup Done in " + time.Since(start).Round(time.Second).String() + "," + "\n" + "Your VPS is ready! You can now run Sidekick launch in your app folder"})
		}()

		if _, err := p.Run(); err != nil {
			fmt.Println("Error running program:", err)
			os.Exit(1)
		}
	},
}

func init() {
	InitCmd.Flags().StringP("server", "s", "", "Set the IP address of your Server")
	InitCmd.Flags().StringP("email", "e", "", "An email address to be used for SSL certs")
	InitCmd.Flags().StringP("name", "n", "", "Set the name of your Server")
	InitCmd.Flags().BoolP("yes", "y", false, "Skip all validation prompts")
}


================================================
FILE: cmd/launch/launch.go
================================================
/*
Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>

Licensed under the GNU GPL License, Version 3.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-3.0.en.html

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package launch

import (
	"context"
	"fmt"
	"io"
	"os"
	"os/exec"
	"strconv"
	"strings"
	"time"

	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/huh"
	"github.com/charmbracelet/log"
	"github.com/docker/docker/api/types/build"
	"github.com/docker/docker/client"
	"github.com/mightymoud/sidekick/render"
	"github.com/mightymoud/sidekick/utils"
	"github.com/spf13/cobra"
	"golang.org/x/crypto/ssh"
	"gopkg.in/yaml.v3"
)

var dockerClient *client.Client

func getDockerClient() (*client.Client, error) {
	if dockerClient != nil {
		return dockerClient, nil
	}

	cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
	if err != nil {
		return nil, err
	}

	dockerClient = cli

	return cli, nil
}

func prelude(server *utils.SidekickServer) string {
	if server.SecretKey == "" {
		render.GetLogger(log.Options{Prefix: "Backward Compat"}).Error("Recent changes to how Sidekick handles secrets prevents you from launcing a new application.")
		render.GetLogger(log.Options{Prefix: "Backward Compat"}).Info("To fix this, run `Sidekick init` with the same server address you have now.")
		render.GetLogger(log.Options{Prefix: "Backward Compat"}).Info("Learn more at www.sidekickdeploy.com/docs/design/encryption")
		os.Exit(1)
	}

	if utils.FileExists("./sidekick.yml") {
		render.GetLogger(log.Options{Prefix: "Sidekick Setup"}).Error("Sidekick config exists in this project.")
		render.GetLogger(log.Options{Prefix: "Sidekick Setup"}).Info("You can deploy a new version of your application with Sidekick deploy.")
		os.Exit(1)
	}

	if utils.FileExists("./Dockerfile") {
		render.GetLogger(log.Options{Prefix: "Dockerfile"}).Info("Detected - scanning file for details")
	} else {
		render.GetLogger(log.Options{Prefix: "Dockerfile"}).Fatal("No dockerfile found in current directory.")
	}

	res, err := os.ReadFile("./Dockerfile")
	if err != nil {
		render.GetLogger(log.Options{Prefix: "Dockerfile"}).Fatal("Unable to process your dockerfile")
	}

	appPort := ""
	for _, line := range strings.Split(string(res), "\n") {
		if strings.HasPrefix(line, "EXPOSE ") {
			appPort = strings.TrimPrefix(line, "EXPOSE ")
		}
	}
	return appPort
}

func stage1(server *utils.SidekickServer) (*ssh.Client, error) {
	sshClient, err := utils.Login(server.Address, "sidekick")
	return sshClient, err
}

func stage2(appName string, p *tea.Program, server *utils.SidekickServer) error {
	cwd, _ := os.Getwd()
	cwdTar, err := utils.TarDirectoryToReader(cwd)
	if err != nil {
		return err
	}

	dockerClient, err := getDockerClient()
	if err != nil {
		return err
	}

	ctx := context.Background()
	resp, err := dockerClient.ImageBuild(ctx, cwdTar, build.ImageBuildOptions{
		Tags:     []string{fmt.Sprintf("%s:latest", appName)},
		Platform: server.PlatformId,
	})
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	render.SendDockerBuildLogsToTUI(resp.Body, p)
	time.Sleep(time.Millisecond * 100)
	return nil
}

func stage3(appName string, p *tea.Program) error {
	ctx := context.Background()
	imageReader, err := dockerClient.ImageSave(ctx, []string{fmt.Sprintf("%s:latest", appName)})
	if err != nil {
		return err
	}
	defer imageReader.Close()

	imgFileName := fmt.Sprintf("%s-latest.tar", appName)
	outFile, err := os.Create(imgFileName)
	if err != nil {
		return err
	}
	defer outFile.Close()

	if _, err := io.Copy(outFile, imageReader); err != nil {
		return err
	}

	return nil
}

func stage4(sshClient *ssh.Client, appName string, p *tea.Program, server *utils.SidekickServer) error {
	_, _, sessionErr := utils.RunCommand(sshClient, fmt.Sprintf("mkdir %s", appName))
	if sessionErr != nil {
		p.Send(render.ErrorMsg{ErrorStr: sessionErr.Error()})
	}
	imgFileName := fmt.Sprintf("%s-latest.tar", appName)
	remoteDist := fmt.Sprintf("%s@%s:./%s", "sidekick", server.Address, appName)
	imgMoveCmd := exec.Command("scp", "-C", imgFileName, remoteDist)
	imgMoveCmdErrorPipe, _ := imgMoveCmd.StderrPipe()
	go render.SendLogsToTUI(imgMoveCmdErrorPipe, p)

	if imgMovCmdErr := imgMoveCmd.Run(); imgMovCmdErr != nil {
		return imgMovCmdErr
	}
	defer os.Remove(imgFileName)
	dockerLoadOutChan, _, sessionErr := utils.RunCommand(sshClient, fmt.Sprintf("cd %s && docker load -i %s && rm %s", appName, imgFileName, imgFileName))
	go func() {
		p.Send(render.LogMsg{LogLine: <-dockerLoadOutChan + "\n"})
		time.Sleep(time.Millisecond * 50)
	}()
	if sessionErr != nil {
		time.Sleep(time.Millisecond * 100)
		p.Send(render.ErrorMsg{ErrorStr: sessionErr.Error()})
	}
	return nil
}

func stage5(sshClient *ssh.Client, appName string, appPort string, appDomain string, hasEnvFile bool, envFileName string, envFileChecksum string, p *tea.Program, server *utils.SidekickServer) error {
	rsyncCmd := exec.Command("rsync", "docker-compose.yaml", fmt.Sprintf("%s@%s:%s", "sidekick", server.Address, fmt.Sprintf("./%s", appName)))
	rsyncCmErr := rsyncCmd.Run()
	if rsyncCmErr != nil {
		return rsyncCmErr
	}

	if hasEnvFile {
		encryptSync := exec.Command("rsync", "encrypted.env", fmt.Sprintf("%s@%s:%s", "sidekick", server.Address, fmt.Sprintf("./%s", appName)))
		encryptSyncErr := encryptSync.Run()
		if encryptSyncErr != nil {
			return encryptSyncErr
		}

		runAppCmdOutChan, _, sessionErr1 := utils.RunCommand(sshClient, fmt.Sprintf(`cd %s && export SOPS_AGE_KEY=%s && sops exec-env encrypted.env 'docker compose -p sidekick up -d'`, appName, server.SecretKey))
		go func() {
			p.Send(render.LogMsg{LogLine: <-runAppCmdOutChan + "\n"})
			time.Sleep(time.Millisecond * 50)
		}()
		if sessionErr1 != nil {
			return sessionErr1
		}
	} else {
		runAppCmdOutChan, _, sessionErr1 := utils.RunCommand(sshClient, fmt.Sprintf(`cd %s && docker compose -p sidekick up -d`, appName))
		go func() {
			p.Send(render.LogMsg{LogLine: <-runAppCmdOutChan + "\n"})
			time.Sleep(time.Millisecond * 50)
		}()
		if sessionErr1 != nil {
			return sessionErr1
		}
	}

	portNumber, err := strconv.ParseUint(appPort, 0, 64)
	if err != nil {
		return err
	}
	envConfig := utils.SidekickAppEnvConfig{}
	if hasEnvFile {
		envConfig.File = envFileName
		envConfig.Hash = envFileChecksum
	}
	// save app config in same folder
	sidekickAppConfig := utils.SidekickAppConfig{
		Name:      appName,
		Version:   "V1",
		Port:      portNumber,
		Url:       appDomain,
		CreatedAt: time.Now().Format(time.UnixDate),
		Env:       envConfig,
		Server:    server.Name,
	}
	ymlData, _ := yaml.Marshal(&sidekickAppConfig)
	os.WriteFile("./sidekick.yml", ymlData, 0644)
	return nil
}

var LaunchCmd = &cobra.Command{
	Use:   "launch",
	Short: "Launch a new application to host on your VPS with Sidekick",
	Long:  `This command will run you through the basic setup to add a new application to your VPS.`,
	Run: func(cmd *cobra.Command, args []string) {
		start := time.Now()

		config, err := utils.GetSidekickConfigFromCmdContext(cmd)
		if err != nil {
			render.GetLogger(log.Options{Prefix: "Sidekick Config"}).Fatalf("%s", err)
		}
		var selectedCtx utils.SidekickContext
		options := make([]huh.Option[utils.SidekickContext], 0, len(config.Contexts))
		for _, c := range config.Contexts {
			server, err := config.FindServer(c.Server)
			if err != nil {
				render.GetLogger(log.Options{Prefix: "Sidekick Config"}).Fatalf("%s", err)
			}
			options = append(options, huh.NewOption(fmt.Sprintf("%s (%s)", server.Name, server.Address), c))
		}
		form := huh.NewForm(
			huh.NewGroup(
				huh.NewSelect[utils.SidekickContext]().
					Title("Select a VPS").
					Options(options...).
					Value(&selectedCtx),
			),
		)
		err = form.Run()

		if err != nil {
			render.GetLogger(log.Options{Prefix: "Context Selection"}).Fatalf("%s", err)
		}

		sidekickServer, err := config.FindServerByContext(selectedCtx.Name)
		if err != nil {
			render.GetLogger(log.Options{Prefix: "Sidekick Config"}).Fatalf("%s", err)
		}

		appPort := prelude(&sidekickServer)

		appName := render.GenerateTextQuestion("Please enter your app url friendly app name", "", "will identify your app containers")
		appPort = render.GenerateTextQuestion("Please enter the port at which the app receives request", appPort, "")
		appDomain := render.GenerateTextQuestion("Please enter the domain to point the app to", fmt.Sprintf("%s.%s.sslip.io", appName, sidekickServer.Address), "must point to your VPS address")
		envFileName := render.GenerateTextQuestion("Please enter which env file you would like to load", ".env", "")

		hasEnvFile := false
		dockerEnvProperty := []string{}
		envFileChecksum := ""
		if utils.FileExists(fmt.Sprintf("./%s", envFileName)) {
			hasEnvFile = true
			render.GetLogger(log.Options{Prefix: "Env File"}).Infof("Detected - Loading env vars from %s", envFileName)
			envHandleErr := utils.HandleEnvFile(envFileName, &dockerEnvProperty, &envFileChecksum, sidekickServer.PublicKey)
			if envHandleErr != nil {
				render.GetLogger(log.Options{Prefix: "Env File"}).Fatalf("Something went wrong %s", envHandleErr)
			}
			defer os.Remove("encrypted.env")
		} else {
			render.GetLogger(log.Options{Prefix: "Env File"}).Info("Not Detected - Skipping env parsing")
		}

		// make a docker service
		imageName := appName
		newService := utils.DockerService{
			Image:   imageName,
			Restart: "unless-stopped",
			Labels: []string{
				"traefik.enable=true",
				fmt.Sprintf("traefik.http.routers.%s.rule=Host(`%s`)", appName, appDomain),
				fmt.Sprintf("traefik.http.services.%s.loadbalancer.server.port=%s", appName, appPort),
				fmt.Sprintf("traefik.http.routers.%s.tls=true", appName),
				fmt.Sprintf("traefik.http.routers.%s.tls.certresolver=default", appName),
				"traefik.docker.network=sidekick",
			},
			Environment: dockerEnvProperty,
			Networks: []string{
				"sidekick",
			},
		}
		newDockerCompose := utils.DockerComposeFile{
			Services: map[string]utils.DockerService{
				appName: newService,
			},
			Networks: map[string]utils.DockerNetwork{
				"sidekick": {
					External: true,
				},
			},
		}
		dockerComposeFile, err := yaml.Marshal(&newDockerCompose)
		if err != nil {
			fmt.Printf("Error marshalling YAML: %v\n", err)
			return
		}
		err = os.WriteFile("docker-compose.yaml", dockerComposeFile, 0644)
		if err != nil {
			fmt.Printf("Error writing file: %v\n", err)
			return
		}
		defer os.Remove("docker-compose.yaml")

		cmdStages := []render.Stage{
			render.MakeStage("Validating connection with VPS", "VPS is reachable", false),
			render.MakeStage("Building latest docker image of your app", "Latest docker image built", true),
			render.MakeStage("Saving docker image locally", "Image saved successfully", false),
			render.MakeStage("Moving image to your server", "Image moved and loaded successfully", false),
			render.MakeStage("Setting up your application", "Application setup successfully", false),
		}
		p := tea.NewProgram(render.TuiModel{
			Stages:      cmdStages,
			BannerMsg:   "Launching your application on your VPS 🚀",
			ActiveIndex: 0,
			Quitting:    false,
			AllDone:     false,
		})

		go func() {
			sshClient, err := stage1(&sidekickServer)
			if err != nil {
				p.Send(render.ErrorMsg{ErrorStr: "Something went wrong logging in to your VPS"})
			}

			time.Sleep(time.Millisecond * 100)
			p.Send(render.NextStageMsg{})

			if err = stage2(appName, p, &sidekickServer); err != nil {
				p.Send(render.ErrorMsg{ErrorStr: fmt.Sprintf("Something went wrong building your docker image: %s", err)})
			}

			time.Sleep(time.Millisecond * 100)
			p.Send(render.NextStageMsg{})

			if err = stage3(appName, p); err != nil {
				p.Send(render.ErrorMsg{ErrorStr: fmt.Sprintf("Something went wrong saving docker image to a file: %s", err)})
			}

			time.Sleep(time.Millisecond * 100)
			p.Send(render.NextStageMsg{})

			if err = stage4(sshClient, appName, p, &sidekickServer); err != nil {
				p.Send(render.ErrorMsg{ErrorStr: fmt.Sprintf("Something went wrong moving the image to your VPS: %s", err)})
			}

			time.Sleep(time.Millisecond * 100)
			p.Send(render.NextStageMsg{})

			if err = stage5(sshClient, appName, appPort, appDomain, hasEnvFile, envFileName, envFileChecksum, p, &sidekickServer); err != nil {
				p.Send(render.ErrorMsg{ErrorStr: fmt.Sprintf("Something went wrong booting up your app: %s", err)})
			}

			p.Send(render.AllDoneMsg{Message: "🚀 Deployed successfully in " + time.Since(start).Round(time.Second).String() + ".\n" + "😎 View your app at https://" + appDomain})
		}()

		if _, err := p.Run(); err != nil {
			fmt.Println("Error running program:", err)
			os.Exit(1)
		}
	},
}


================================================
FILE: cmd/preview/list/list.go
================================================
/*
Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>

Licensed under the GNU GPL License, Version 3.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-3.0.en.html

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package previewList

import (
	"fmt"
	"os"

	"github.com/charmbracelet/huh"
	"github.com/charmbracelet/lipgloss"
	"github.com/charmbracelet/lipgloss/table"
	"github.com/charmbracelet/log"
	"github.com/mightymoud/sidekick/render"
	"github.com/mightymoud/sidekick/utils"
	"github.com/spf13/cobra"
)

// listCmd represents the list command
var ListCmd = &cobra.Command{
	Use:     "list",
	Aliases: []string{"ls"},
	Short:   "This command lists all the preview environments",
	Long:    `This command lists all the preview environments that are currently running on your VPS.`,
	Run: func(cmd *cobra.Command, args []string) {
		appConfig, appConfigErr := utils.LoadAppConfig()
		if appConfigErr != nil {
			log.Fatalf("Unable to load your config file. Might be corrupted")
		}
		if len(appConfig.PreviewEnvs) == 0 {
			render.GetLogger(log.Options{Prefix: "Preview Envs"}).Info("Not Found in current project")
			os.Exit(0)
		}
		header := lipgloss.NewStyle().Foreground(lipgloss.Color("77")).MarginTop(1).MarginLeft(1).Render("Currently running preview envs:")
		tableString := table.New().
			Border(lipgloss.RoundedBorder()).
			BorderStyle(lipgloss.NewStyle().Foreground(lipgloss.Color("99"))).
			StyleFunc(func(row, col int) lipgloss.Style {
				switch {
				case row == 0:
					return lipgloss.NewStyle().Foreground(lipgloss.Color("60")).Align(lipgloss.Center)
				default:
					return lipgloss.NewStyle().Foreground(lipgloss.Color("78")).PaddingLeft(1).PaddingRight(1)
				}
			}).
			Headers("Commit", "Image", "Deployed At", "URL")

		hashSlice := []huh.Option[string]{}
		for v := range appConfig.PreviewEnvs {
			hashSlice = append(hashSlice, huh.NewOption(v, v))
			tableString.Row(v, appConfig.PreviewEnvs[v].Image, appConfig.PreviewEnvs[v].CreatedAt, appConfig.PreviewEnvs[v].Url)
		}
		fmt.Println(header)
		fmt.Println(tableString)
	},
}


================================================
FILE: cmd/preview/preview.go
================================================
/*
Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>

Licensed under the GNU GPL License, Version 3.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-3.0.en.html

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package preview

import (
	"fmt"
	"os"
	"os/exec"
	"strings"
	"time"

	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/log"
	previewList "github.com/mightymoud/sidekick/cmd/preview/list"
	previewRemove "github.com/mightymoud/sidekick/cmd/preview/remove"
	"github.com/mightymoud/sidekick/render"
	"github.com/mightymoud/sidekick/utils"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"gopkg.in/yaml.v3"
)

var PreviewCmd = &cobra.Command{
	Use:   "preview",
	Short: "Deploy a preview environment for your application",
	Long:  `Sidekick allows you to deploy preview environment based on commit hash`,
	Run: func(cmd *cobra.Command, args []string) {
		start := time.Now()

		config, err := utils.GetSidekickConfigFromCmdContext(cmd)
		if err != nil {
			render.GetLogger(log.Options{Prefix: "Sidekick Config"}).Fatalf("%s", err)
		}
		sidekickServer, err := config.FindServerByContext(config.CurrentContext)
		if err != nil {
			render.GetLogger(log.Options{Prefix: "Sidekick Config"}).Fatalf("%s", err)
		}

		appConfig, appConfigErr := utils.LoadAppConfig()
		if appConfigErr != nil {
			render.GetLogger(log.Options{Prefix: "Sidekick Setup"}).Error("Sidekick config exits in this project.")
			render.GetLogger(log.Options{Prefix: "Sidekick Setup"}).Info("You can deploy a new version of your application with Sidekick deploy.")
			os.Exit(1)
		}

		if sidekickServer.SecretKey == "" {
			render.GetLogger(log.Options{Prefix: "Backward Compat"}).Error("Recent changes to how Sidekick handles secrets prevents you from launcing a new application.")
			render.GetLogger(log.Options{Prefix: "Backward Compat"}).Info("To fix this, run `Sidekick init` with the same server address you have now.")
			render.GetLogger(log.Options{Prefix: "Backward Compat"}).Info("Learn more at www.sidekickdeploy.com/docs/design/encryption")
			os.Exit(1)
		}

		gitTreeCheck := exec.Command("sh", "-s", "-")
		gitTreeCheck.Stdin = strings.NewReader(utils.CheckGitTreeScript)
		output, _ := gitTreeCheck.Output()
		if string(output) != "all good\n" {
			render.GetLogger(log.Options{Prefix: "Preview Cmd"}).Error("Please commit any changes to git before deploying a preview environment")
			os.Exit(1)
		}

		gitShortHashCmd := exec.Command("sh", "-s", "-")
		gitShortHashCmd.Stdin = strings.NewReader("git rev-parse --short HEAD")
		hashOutput, hashErr := gitShortHashCmd.Output()
		if hashErr != nil {
			render.GetLogger(log.Options{Prefix: "Preview Cmd"}).Error("Issue occurred getting git commit hash: %s", hashErr)
			os.Exit(1)
		}
		deployHash := strings.TrimSuffix(string(hashOutput), "\n")

		cmdStages := []render.Stage{
			render.MakeStage("Validating connection with VPS", "VPS is reachable", false),
			render.MakeStage("Building latest docker image of your app", "Latest docker image built", true),
			render.MakeStage("Saving docker image locally", "Image saved successfully", false),
			render.MakeStage("Moving image to your server", "Image moved and loaded successfully", false),
			render.MakeStage("Deploying a preview env of your application", "Preview env setup successfully", false),
		}
		p := tea.NewProgram(render.TuiModel{
			Stages:      cmdStages,
			BannerMsg:   "Deploying a preview env of your app 😎",
			ActiveIndex: 0,
			Quitting:    false,
			AllDone:     false,
		})

		go func() {
			sshClient, err := utils.Login(viper.GetString("serverAddress"), "sidekick")
			if err != nil {
				p.Send(render.ErrorMsg{})
			}
			p.Send(render.NextStageMsg{})

			dockerEnvProperty := []string{}
			envFileChecksum := ""
			if appConfig.Env.File != "" {
				envErr := utils.HandleEnvFile(appConfig.Env.File, &dockerEnvProperty, &envFileChecksum, sidekickServer.PublicKey)
				if envErr != nil {
					panic(envErr)
				}
			}

			imageName := fmt.Sprintf("%s:%s", appConfig.Name, deployHash)
			serviceName := fmt.Sprintf("%s-%s", appConfig.Name, deployHash)
			previewURL := fmt.Sprintf("%s.%s", deployHash, appConfig.Url)
			newService := utils.DockerService{
				Image: imageName,
				Labels: []string{
					"traefik.enable=true",
					fmt.Sprintf("traefik.http.routers.%s.rule=Host(`%s`)", serviceName, previewURL),
					fmt.Sprintf("traefik.http.services.%s.loadbalancer.server.port=%s", serviceName, fmt.Sprint(appConfig.Port)),
					fmt.Sprintf("traefik.http.routers.%s.tls=true", serviceName),
					fmt.Sprintf("traefik.http.routers.%s.tls.certresolver=default", serviceName),
					"traefik.docker.network=sidekick",
				},
				Environment: dockerEnvProperty,
				Networks: []string{
					"sidekick",
				},
			}
			newDockerCompose := utils.DockerComposeFile{
				Services: map[string]utils.DockerService{
					serviceName: newService,
				},
				Networks: map[string]utils.DockerNetwork{
					"sidekick": {
						External: true,
					},
				},
			}
			dockerComposeFile, err := yaml.Marshal(&newDockerCompose)
			if err != nil {
				fmt.Printf("Error marshalling YAML: %v\n", err)
				return
			}
			err = os.WriteFile("docker-compose.yaml", dockerComposeFile, 0644)
			if err != nil {
				fmt.Printf("Error writing file: %v\n", err)
				return
			}

			cwd, _ := os.Getwd()
			dockerImage := fmt.Sprintf("%s:%s", appConfig.Name, deployHash)
			dockerBuildCmd := exec.Command("docker", "build", "--tag", dockerImage, "--progress=plain", "--platform=linux/amd64", cwd)
			dockerBuildCmdErrPipe, _ := dockerBuildCmd.StderrPipe()
			go render.SendLogsToTUI(dockerBuildCmdErrPipe, p)

			if dockerBuildErr := dockerBuildCmd.Run(); dockerBuildErr != nil {
				p.Send(render.ErrorMsg{})
			}

			time.Sleep(time.Millisecond * 100)

			p.Send(render.NextStageMsg{})

			imgFileName := fmt.Sprintf("%s-%s.tar", appConfig.Name, deployHash)
			imgSaveCmd := exec.Command("docker", "save", "-o", imgFileName, dockerImage)
			imgSaveCmdErrPipe, _ := imgSaveCmd.StderrPipe()
			go render.SendLogsToTUI(imgSaveCmdErrPipe, p)

			if imgSaveCmdErr := imgSaveCmd.Run(); imgSaveCmdErr != nil {
				p.Send(render.ErrorMsg{})
			}

			time.Sleep(time.Millisecond * 100)

			p.Send(render.NextStageMsg{})

			_, _, sessionErr0 := utils.RunCommand(sshClient, fmt.Sprintf(`mkdir -p %s/preview/%s`, appConfig.Name, deployHash))
			if sessionErr0 != nil {
				p.Send(render.ErrorMsg{ErrorStr: sessionErr0.Error()})
			}

			remoteDist := fmt.Sprintf("%s@%s:./%s", "sidekick", viper.GetString("serverAddress"), appConfig.Name)
			imgMoveCmd := exec.Command("scp", "-C", imgFileName, remoteDist)
			imgMoveCmdErrorPipe, _ := imgMoveCmd.StderrPipe()
			go render.SendLogsToTUI(imgMoveCmdErrorPipe, p)

			if imgMovCmdErr := imgMoveCmd.Run(); imgMovCmdErr != nil {
				p.Send(render.ErrorMsg{})
			}

			time.Sleep(time.Millisecond * 200)

			dockerLoadOutChan, _, sessionErr := utils.RunCommand(sshClient, fmt.Sprintf("cd %s && docker load -i %s && rm %s", appConfig.Name, imgFileName, imgFileName))
			go func() {
				p.Send(render.LogMsg{LogLine: <-dockerLoadOutChan + "\n"})
				time.Sleep(time.Millisecond * 50)
			}()
			if sessionErr != nil {
				time.Sleep(time.Millisecond * 100)
				p.Send(render.ErrorMsg{ErrorStr: sessionErr.Error()})
			}

			time.Sleep(time.Millisecond * 100)
			p.Send(render.NextStageMsg{})

			previewFolder := fmt.Sprintf("./%s/preview/%s", appConfig.Name, deployHash)
			rsyncCmd := exec.Command("rsync", "docker-compose.yaml", fmt.Sprintf("%s@%s:%s", "sidekick", viper.GetString("serverAddress"), previewFolder))
			rsyncCmErr := rsyncCmd.Run()
			if rsyncCmErr != nil {
				p.Send(render.ErrorMsg{ErrorStr: rsyncCmErr.Error()})
			}

			if appConfig.Env.File != "" {
				encryptSync := exec.Command("rsync", "encrypted.env", fmt.Sprintf("%s@%s:%s", "sidekick", viper.GetString("serverAddress"), previewFolder))
				encryptSyncErrr := encryptSync.Run()
				if encryptSyncErrr != nil {
					p.Send(render.ErrorMsg{ErrorStr: encryptSyncErrr.Error()})
				}

				runAppCmdOutChan, _, sessionErr1 := utils.RunCommand(sshClient, fmt.Sprintf(`cd %s && export SOPS_AGE_KEY=%s && sops exec-env encrypted.env 'docker compose -p sidekick up -d'`, previewFolder, viper.GetString("secretKey")))
				go func() {
					p.Send(render.LogMsg{LogLine: <-runAppCmdOutChan + "\n"})
					time.Sleep(time.Millisecond * 50)
				}()
				if sessionErr1 != nil {
					p.Send(render.ErrorMsg{ErrorStr: sessionErr1.Error()})
				}
			} else {
				runAppCmdOutChan, _, sessionErr1 := utils.RunCommand(sshClient, fmt.Sprintf(`cd %s && docker compose -p sidekick up -d`, previewFolder))
				go func() {
					p.Send(render.LogMsg{LogLine: <-runAppCmdOutChan + "\n"})
					time.Sleep(time.Millisecond * 50)
				}()
				if sessionErr1 != nil {
					p.Send(render.ErrorMsg{ErrorStr: sessionErr1.Error()})
				}
			}
			previewEnvConfig := utils.SidekickPreview{
				Url:       fmt.Sprintf("https://%s", previewURL),
				Image:     imageName,
				CreatedAt: time.Now().Format(time.UnixDate),
			}
			if len(appConfig.PreviewEnvs) == 0 {
				appConfig.PreviewEnvs = map[string]utils.SidekickPreview{}
			}
			appConfig.PreviewEnvs[deployHash] = previewEnvConfig

			ymlData, _ := yaml.Marshal(&appConfig)
			os.WriteFile("./sidekick.yml", ymlData, 0644)

			os.Remove("docker-compose.yaml")
			os.Remove("encrypted.env")
			os.Remove(imgFileName)

			p.Send(render.AllDoneMsg{Message: "🚀 Deployed successfully in " + time.Since(start).Round(time.Second).String() + ".\n" + "😎 View your app at https://" + previewURL})

		}()

		if _, err := p.Run(); err != nil {
			fmt.Println("Error running program:", err)
			os.Exit(1)
		}
	},
}

func init() {
	PreviewCmd.AddCommand(previewList.ListCmd)
	PreviewCmd.AddCommand(previewRemove.RemoveCmd)
}


================================================
FILE: cmd/preview/remove/remove.go
================================================
/*
Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>

Licensed under the GNU GPL License, Version 3.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-3.0.en.html

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package previewRemove

import (
	"fmt"
	"os"

	"github.com/charmbracelet/huh"
	"github.com/charmbracelet/huh/spinner"
	"github.com/charmbracelet/lipgloss"
	"github.com/charmbracelet/lipgloss/table"
	"github.com/charmbracelet/log"
	"github.com/mightymoud/sidekick/render"
	"github.com/mightymoud/sidekick/utils"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"gopkg.in/yaml.v3"
)

var RemoveCmd = &cobra.Command{
	Use:     "remove",
	Aliases: []string{"rm"},
	Short:   "This command removes a preview environment",
	Long:    "This command removes a preview environment by the git hash associated with them",
	Run: func(cmd *cobra.Command, args []string) {
		if configErr := utils.ViperInit(); configErr != nil {
			render.GetLogger(log.Options{Prefix: "Sidekick Config"}).Fatal("Not found - Run Sidekick init first")
		}
		if !utils.FileExists("./sidekick.yml") {
			render.GetLogger(log.Options{Prefix: "Project Config"}).Fatal("Not found in current directory Run sidekick launch")
		}

		appConfig, appConfigErr := utils.LoadAppConfig()
		if appConfigErr != nil {
			log.Fatalf("Unable to load your config file. Might be corrupted")
		}

		var selected string
		var confirm bool

		if len(appConfig.PreviewEnvs) == 0 {
			render.GetLogger(log.Options{Prefix: "Preview Envs"}).Info("Not Found in current project")
			os.Exit(0)
		}

		header := lipgloss.NewStyle().Foreground(lipgloss.Color("77")).MarginTop(1).MarginLeft(1).Render("Currently running preview envs:")
		tableString := table.New().
			Border(lipgloss.RoundedBorder()).
			BorderStyle(lipgloss.NewStyle().Foreground(lipgloss.Color("99"))).
			StyleFunc(func(row, col int) lipgloss.Style {
				switch {
				case row == 0:
					return lipgloss.NewStyle().Foreground(lipgloss.Color("60")).Align(lipgloss.Center)
				default:
					return lipgloss.NewStyle().Foreground(lipgloss.Color("78")).PaddingLeft(1).PaddingRight(1)
				}
			}).
			Headers("Commit", "Image", "Deployed At", "URL")

		hashSlice := []huh.Option[string]{}
		for v := range appConfig.PreviewEnvs {
			hashSlice = append(hashSlice, huh.NewOption(v, v))
			tableString.Row(v, appConfig.PreviewEnvs[v].Image, appConfig.PreviewEnvs[v].CreatedAt, appConfig.PreviewEnvs[v].Url)
		}
		fmt.Println(header)
		fmt.Println(tableString)
		huh.NewSelect[string]().
			Title("Which preview env would you like to delete?").
			Options(hashSlice...).
			Value(&selected).
			Run()
		huh.NewConfirm().
			Title("Are you sure?").
			Affirmative("Yes!").
			Negative("No.").
			Value(&confirm).
			Run()
		if !confirm {
			os.Exit(0)
		} else {
			action := func() {
				deletePreviewEnv(selected)
			}
			spinner.New().
				Title("Deleting your selected preview environment...").
				Action(action).
				Run()

			fmt.Println("Preview env deleted successfully!")
		}

	},
}

func deletePreviewEnv(hash string) {

	appConfig, appConfigErr := utils.LoadAppConfig()
	if appConfigErr != nil {
		log.Fatalf("Unable to load your config file. Might be corrupted")
	}
	sshClient, err := utils.Login(viper.GetString("serverAddress"), "sidekick")
	if err != nil {
		log.Fatal("Unable to login to your VPS")
	}

	_, _, dockerDwnErr := utils.RunCommand(sshClient, fmt.Sprintf("cd %s/preview/%s && docker rm -f sidekick-%s-%s-1 && docker image rm %s:%s", appConfig.Name, hash, appConfig.Name, hash, appConfig.Name, hash))
	if dockerDwnErr != nil {
		log.Fatalf("Issue happened stopping your service: %s", dockerDwnErr)
	}
	_, _, folderRmErr := utils.RunCommand(sshClient, fmt.Sprintf("rm -rf %s/preview/%s", appConfig.Name, hash))
	if folderRmErr != nil {
		log.Fatalf("Issue happened deleting the preview folder: %s", folderRmErr)
	}

	delete(appConfig.PreviewEnvs, hash)
	ymlData, _ := yaml.Marshal(&appConfig)
	os.WriteFile("./sidekick.yml", ymlData, 0644)
}


================================================
FILE: cmd/root.go
================================================
/*
Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>

Licensed under the GNU GPL License, Version 3.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-3.0.en.html

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd

import (
	"context"
	"os"
	"path/filepath"

	"github.com/mightymoud/sidekick/cmd/config"
	"github.com/mightymoud/sidekick/cmd/deploy"
	"github.com/mightymoud/sidekick/cmd/initialize"
	"github.com/mightymoud/sidekick/cmd/launch"
	"github.com/mightymoud/sidekick/cmd/preview"
	"github.com/mightymoud/sidekick/utils"
	"github.com/pterm/pterm"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"gopkg.in/yaml.v3"
)

var version = "dev"

var rootCmd = &cobra.Command{
	Use:     "sidekick",
	Version: version,
	Short:   "CLI to self-host all your apps on a single VPS without vendor locking",
	Long:    `With sidekick you can deploy any number of applications to a single VPS, connect multiple domains and much more.`,
	PersistentPreRun: func(cmd *cobra.Command, args []string) {
		initConfig(cmd)
	},
}

func Execute() {
	err := rootCmd.Execute()
	if err != nil {
		os.Exit(1)
	}
}

func init() {
	rootCmd.SetVersionTemplate(`{{println .Version}}`)

	home, err := os.UserHomeDir()
	if err != nil {
		pterm.Error.Println(err)
		os.Exit(1)
	}
	defaultConfigPath := filepath.Join(home, ".config", "sidekick", "default.yaml")

	rootCmd.PersistentFlags().String("config", defaultConfigPath, "Path to sidekick config file")

	rootCmd.AddCommand(initialize.InitCmd)
	rootCmd.AddCommand(preview.PreviewCmd)
	rootCmd.AddCommand(deploy.DeployCmd)
	rootCmd.AddCommand(launch.LaunchCmd)
	rootCmd.AddCommand(config.ConfigCmd)
}

func initConfig(cmd *cobra.Command) {
	var config utils.SidekickConfig

	viper.BindEnv("config", "SIDEKICK_CONFIG")
	viper.BindPFlag("config", cmd.Flags().Lookup("config"))

	configPath := viper.GetString("config")
	content, err := os.ReadFile(configPath)

	if err != nil {
		if requireConfigFile(cmd) {
			pterm.Fatal.Println("Sidekick config not found - Run sidekick init")
		}
		config = utils.SidekickConfig{
			Version:        "1",
			CurrentContext: "",
			Contexts:       []utils.SidekickContext{},
			Servers:        []utils.SidekickServer{},
		}
	} else {
		err := yaml.Unmarshal(content, &config)
		if err != nil {
			pterm.Fatal.Sprintf("Error unmarshaling the config yaml file: %s", err)
		}
	}

	if config.Version != "1" && !shouldSkipConfigVersionCheck(cmd) {
		pterm.Fatal.Println("An older version of the config file found. Please run 'sidekick config migrate'.")
	}

	ctx := context.WithValue(cmd.Context(), "config", &config)
	cmd.SetContext(ctx)
}

func requireConfigFile(cmd *cobra.Command) bool {
	cmdName := cmd.Name()

	if cmdName == "init" || cmdName == "help" {
		return false
	}

	if parentCmd := cmd.Parent(); parentCmd != nil {
		if parentCmd.Name() == "config" && cmdName == "migrate" {
			return false
		}
	}

	return true
}

func shouldSkipConfigVersionCheck(cmd *cobra.Command) bool {
	cmdName := cmd.Name()

	if cmdName == "help" {
		return true
	}

	if parentCmd := cmd.Parent(); parentCmd != nil {
		if parentCmd.Name() == "config" && cmdName == "migrate" {
			return true
		}
	}

	return false
}


================================================
FILE: go.mod
================================================
module github.com/mightymoud/sidekick

go 1.24.0

toolchain go1.24.5

require (
	github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7
	github.com/charmbracelet/bubbletea v1.3.6
	github.com/charmbracelet/lipgloss v1.1.0
	github.com/charmbracelet/log v0.4.0
	github.com/docker/docker v28.5.1+incompatible
	github.com/joho/godotenv v1.5.1
	github.com/skeema/knownhosts v1.3.0
	github.com/spf13/cobra v1.8.1
	github.com/spf13/viper v1.19.0
	golang.org/x/crypto v0.45.0
	gopkg.in/yaml.v3 v3.0.1
)

require (
	atomicgo.dev/cursor v0.2.0 // indirect
	atomicgo.dev/keyboard v0.2.9 // indirect
	atomicgo.dev/schedule v0.1.0 // indirect
	github.com/Microsoft/go-winio v0.6.2 // indirect
	github.com/atotto/clipboard v0.1.4 // indirect
	github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
	github.com/catppuccin/go v0.3.0 // indirect
	github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect
	github.com/charmbracelet/x/ansi v0.9.3 // indirect
	github.com/charmbracelet/x/cellbuf v0.0.13 // indirect
	github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect
	github.com/charmbracelet/x/term v0.2.1 // indirect
	github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 // indirect
	github.com/containerd/errdefs v1.0.0 // indirect
	github.com/containerd/errdefs/pkg v0.3.0 // indirect
	github.com/containerd/log v0.1.0 // indirect
	github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
	github.com/distribution/reference v0.6.0 // indirect
	github.com/docker/go-connections v0.6.0 // indirect
	github.com/docker/go-units v0.5.0 // indirect
	github.com/dustin/go-humanize v1.0.1 // indirect
	github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
	github.com/felixge/httpsnoop v1.0.4 // indirect
	github.com/fsnotify/fsnotify v1.7.0 // indirect
	github.com/go-logfmt/logfmt v0.6.0 // indirect
	github.com/go-logr/logr v1.4.3 // indirect
	github.com/go-logr/stdr v1.2.2 // indirect
	github.com/gookit/color v1.5.4 // indirect
	github.com/hashicorp/hcl v1.0.0 // indirect
	github.com/lithammer/fuzzysearch v1.1.8 // indirect
	github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
	github.com/magiconair/properties v1.8.7 // indirect
	github.com/mattn/go-isatty v0.0.20 // indirect
	github.com/mattn/go-localereader v0.0.1 // indirect
	github.com/mattn/go-runewidth v0.0.16 // indirect
	github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect
	github.com/mitchellh/mapstructure v1.5.0 // indirect
	github.com/moby/docker-image-spec v1.3.1 // indirect
	github.com/moby/moby v28.5.2+incompatible // indirect
	github.com/moby/sys/atomicwriter v0.1.0 // indirect
	github.com/moby/term v0.5.2 // indirect
	github.com/morikuni/aec v1.0.0 // indirect
	github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
	github.com/muesli/cancelreader v0.2.2 // indirect
	github.com/muesli/reflow v0.3.0 // indirect
	github.com/muesli/termenv v0.16.0 // indirect
	github.com/opencontainers/go-digest v1.0.0 // indirect
	github.com/opencontainers/image-spec v1.1.1 // indirect
	github.com/pelletier/go-toml/v2 v2.2.2 // indirect
	github.com/pkg/errors v0.9.1 // indirect
	github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
	github.com/rivo/uniseg v0.4.7 // indirect
	github.com/sagikazarmark/locafero v0.4.0 // indirect
	github.com/sagikazarmark/slog-shim v0.1.0 // indirect
	github.com/sahilm/fuzzy v0.1.1 // indirect
	github.com/sourcegraph/conc v0.3.0 // indirect
	github.com/spf13/afero v1.11.0 // indirect
	github.com/spf13/cast v1.6.0 // indirect
	github.com/subosito/gotenv v1.6.0 // indirect
	github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
	go.opentelemetry.io/auto/sdk v1.1.0 // indirect
	go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 // indirect
	go.opentelemetry.io/otel v1.38.0 // indirect
	go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0 // indirect
	go.opentelemetry.io/otel/metric v1.38.0 // indirect
	go.opentelemetry.io/otel/sdk v1.38.0 // indirect
	go.opentelemetry.io/otel/trace v1.38.0 // indirect
	go.uber.org/atomic v1.9.0 // indirect
	go.uber.org/multierr v1.9.0 // indirect
	golang.org/x/exp v0.0.0-20231006140011-7918f672742d // indirect
	golang.org/x/sync v0.18.0 // indirect
	golang.org/x/term v0.37.0 // indirect
	golang.org/x/text v0.31.0 // indirect
	gopkg.in/ini.v1 v1.67.0 // indirect
	gotest.tools/v3 v3.5.2 // indirect
)

require (
	github.com/charmbracelet/huh v0.8.0
	github.com/charmbracelet/huh/spinner v0.0.0-20241011224433-983a50776b31
	github.com/erikgeiser/promptkit v0.9.0
	github.com/inconshreveable/mousetrap v1.1.0 // indirect
	github.com/pterm/pterm v0.12.79
	github.com/spf13/pflag v1.0.5 // indirect
	github.com/stretchr/testify v1.11.1
	golang.org/x/sys v0.38.0 // indirect
)


================================================
FILE: go.sum
================================================
atomicgo.dev/assert v0.0.2 h1:FiKeMiZSgRrZsPo9qn/7vmr7mCsh5SZyXY4YGYiYwrg=
atomicgo.dev/assert v0.0.2/go.mod h1:ut4NcI3QDdJtlmAxQULOmA13Gz6e2DWbSAS8RUOmNYQ=
atomicgo.dev/cursor v0.2.0 h1:H6XN5alUJ52FZZUkI7AlJbUc1aW38GWZalpYRPpoPOw=
atomicgo.dev/cursor v0.2.0/go.mod h1:Lr4ZJB3U7DfPPOkbH7/6TOtJ4vFGHlgj1nc+n900IpU=
atomicgo.dev/keyboard v0.2.9 h1:tOsIid3nlPLZ3lwgG8KZMp/SFmr7P0ssEN5JUsm78K8=
atomicgo.dev/keyboard v0.2.9/go.mod h1:BC4w9g00XkxH/f1HXhW2sXmJFOCWbKn9xrOunSFtExQ=
atomicgo.dev/schedule v0.1.0 h1:nTthAbhZS5YZmgYbb2+DH8uQIZcTlIrd4eYr3UQxEjs=
atomicgo.dev/schedule v0.1.0/go.mod h1:xeUa3oAkiuHYh8bKiQBRojqAMq3PXXbJujjb0hw8pEU=
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg=
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
github.com/MarvinJWendt/testza v0.1.0/go.mod h1:7AxNvlfeHP7Z/hDQ5JtE3OKYT3XFUeLCDE2DQninSqs=
github.com/MarvinJWendt/testza v0.2.1/go.mod h1:God7bhG8n6uQxwdScay+gjm9/LnO4D3kkcZX4hv9Rp8=
github.com/MarvinJWendt/testza v0.2.8/go.mod h1:nwIcjmr0Zz+Rcwfh3/4UhBp7ePKVhuBExvZqnKYWlII=
github.com/MarvinJWendt/testza v0.2.10/go.mod h1:pd+VWsoGUiFtq+hRKSU1Bktnn+DMCSrDrXDpX2bG66k=
github.com/MarvinJWendt/testza v0.2.12/go.mod h1:JOIegYyV7rX+7VZ9r77L/eH6CfJHHzXjB69adAhzZkI=
github.com/MarvinJWendt/testza v0.3.0/go.mod h1:eFcL4I0idjtIx8P9C6KkAuLgATNKpX4/2oUqKc6bF2c=
github.com/MarvinJWendt/testza v0.4.2/go.mod h1:mSdhXiKH8sg/gQehJ63bINcCKp7RtYewEjXsvsVUPbE=
github.com/MarvinJWendt/testza v0.5.2 h1:53KDo64C1z/h/d/stCYCPY69bt/OSwjq5KpFNwi+zB4=
github.com/MarvinJWendt/testza v0.5.2/go.mod h1:xu53QFE5sCdjtMCKk8YMQ2MnymimEctc4n3EjyIYvEY=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/atomicgo/cursor v0.0.1/go.mod h1:cBON2QmmrysudxNBFthvMtN32r3jxVRIvzkUiF/RuIk=
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8=
github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA=
github.com/aymanbagabas/go-udiff v0.3.1 h1:LV+qyBQ2pqe0u42ZsUEtPiCaUoqgA9gYRDs3vj1nolY=
github.com/catppuccin/go v0.2.0 h1:ktBeIrIP42b/8FGiScP9sgrWOss3lw0Z5SktRoithGA=
github.com/catppuccin/go v0.2.0/go.mod h1:8IHJuMGaUUjQM82qBrGNBv7LFq6JI3NnQCF6MOlZjpc=
github.com/catppuccin/go v0.3.0 h1:d+0/YicIq+hSTo5oPuRi5kOpqkVA5tAsU6dNhvRu+aY=
github.com/catppuccin/go v0.3.0/go.mod h1:8IHJuMGaUUjQM82qBrGNBv7LFq6JI3NnQCF6MOlZjpc=
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
github.com/charmbracelet/bubbles v0.20.0 h1:jSZu6qD8cRQ6k9OMfR1WlM+ruM8fkPWkHvQWD9LIutE=
github.com/charmbracelet/bubbles v0.20.0/go.mod h1:39slydyswPy+uVOHZ5x/GjwVAFkCsV8IIVy+4MhzwwU=
github.com/charmbracelet/bubbles v0.21.0 h1:9TdC97SdRVg/1aaXNVWfFH3nnLAwOXr8Fn6u6mfQdFs=
github.com/charmbracelet/bubbles v0.21.0/go.mod h1:HF+v6QUR4HkEpz62dx7ym2xc71/KBHg+zKwJtMw+qtg=
github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7 h1:JFgG/xnwFfbezlUnFMJy0nusZvytYysV4SCS2cYbvws=
github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7/go.mod h1:ISC1gtLcVilLOf23wvTfoQuYbW2q0JevFxPfUzZ9Ybw=
github.com/charmbracelet/bubbletea v1.1.1 h1:KJ2/DnmpfqFtDNVTvYZ6zpPFL9iRCRr0qqKOCvppbPY=
github.com/charmbracelet/bubbletea v1.1.1/go.mod h1:9Ogk0HrdbHolIKHdjfFpyXJmiCzGwy+FesYkZr7hYU4=
github.com/charmbracelet/bubbletea v1.3.4 h1:kCg7B+jSCFPLYRA52SDZjr51kG/fMUEoPoZrkaDHyoI=
github.com/charmbracelet/bubbletea v1.3.4/go.mod h1:dtcUCyCGEX3g9tosuYiut3MXgY/Jsv9nKVdibKKRRXo=
github.com/charmbracelet/bubbletea v1.3.6 h1:VkHIxPJQeDt0aFJIsVxw8BQdh/F/L2KKZGsK6et5taU=
github.com/charmbracelet/bubbletea v1.3.6/go.mod h1:oQD9VCRQFF8KplacJLo28/jofOI2ToOfGYeFgBBxHOc=
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs=
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk=
github.com/charmbracelet/huh v0.6.0 h1:mZM8VvZGuE0hoDXq6XLxRtgfWyTI3b2jZNKh0xWmax8=
github.com/charmbracelet/huh v0.6.0/go.mod h1:GGNKeWCeNzKpEOh/OJD8WBwTQjV3prFAtQPpLv+AVwU=
github.com/charmbracelet/huh v0.8.0 h1:Xz/Pm2h64cXQZn/Jvele4J3r7DDiqFCNIVteYukxDvY=
github.com/charmbracelet/huh v0.8.0/go.mod h1:5YVc+SlZ1IhQALxRPpkGwwEKftN/+OlJlnJYlDRFqN4=
github.com/charmbracelet/huh/spinner v0.0.0-20241011224433-983a50776b31 h1:HqaYBKXy1eQBnN9tCLJJHaQ+3btqonOVh25LZ/Xaxps=
github.com/charmbracelet/huh/spinner v0.0.0-20241011224433-983a50776b31/go.mod h1:Cxhgl8N0sX9A+EQxedzzGZAalaF8fUVL+JP/pSOW8cI=
github.com/charmbracelet/lipgloss v0.13.0 h1:4X3PPeoWEDCMvzDvGmTajSyYPcZM4+y8sCA/SsA3cjw=
github.com/charmbracelet/lipgloss v0.13.0/go.mod h1:nw4zy0SBX/F/eAO1cWdcvy6qnkDUxr8Lw7dvFrAIbbY=
github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=
github.com/charmbracelet/log v0.4.0 h1:G9bQAcx8rWA2T3pWvx7YtPTPwgqpk7D68BX21IRW8ZM=
github.com/charmbracelet/log v0.4.0/go.mod h1:63bXt/djrizTec0l11H20t8FDSvA4CRZJ1KH22MdptM=
github.com/charmbracelet/x/ansi v0.2.3 h1:VfFN0NUpcjBRd4DnKfRaIRo53KRgey/nhOoEqosGDEY=
github.com/charmbracelet/x/ansi v0.2.3/go.mod h1:dk73KoMTT5AX5BsX0KrqhsTqAnhZZoCBjs7dGWp4Ktw=
github.com/charmbracelet/x/ansi v0.8.0 h1:9GTq3xq9caJW8ZrBTe0LIe2fvfLR/bYXKTx2llXn7xE=
github.com/charmbracelet/x/ansi v0.8.0/go.mod h1:wdYl/ONOLHLIVmQaxbIYEC/cRKOQyjTkowiI4blgS9Q=
github.com/charmbracelet/x/ansi v0.9.3 h1:BXt5DHS/MKF+LjuK4huWrC6NCvHtexww7dMayh6GXd0=
github.com/charmbracelet/x/ansi v0.9.3/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE=
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8=
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=
github.com/charmbracelet/x/cellbuf v0.0.13 h1:/KBBKHuVRbq1lYx5BzEHBAFBP8VcQzJejZ/IA3iR28k=
github.com/charmbracelet/x/cellbuf v0.0.13/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=
github.com/charmbracelet/x/exp/golden v0.0.0-20240815200342-61de596daa2b h1:MnAMdlwSltxJyULnrYbkZpp4k58Co7Tah3ciKhSNo0Q=
github.com/charmbracelet/x/exp/golden v0.0.0-20240815200342-61de596daa2b/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=
github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ=
github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 h1:qko3AQ4gK1MTS/de7F5hPGx6/k1u0w4TeYmBFwzYVP4=
github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0/go.mod h1:pBhA0ybfXv6hDjQUZ7hk1lVxBiUbupdw5R31yPUViVQ=
github.com/charmbracelet/x/term v0.2.0 h1:cNB9Ot9q8I711MyZ7myUR5HFWL/lc3OpU8jZ4hwm0x0=
github.com/charmbracelet/x/term v0.2.0/go.mod h1:GVxgxAbjUrmpvIINHIQnJJKpMlHiZ4cktEQCN6GWyF0=
github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
github.com/containerd/console v1.0.3/go.mod h1:7LqA/THxQ86k76b8c/EMSiaJ3h1eZkMkXar0TQ1gf3U=
github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 h1:q2hJAaP1k2wIvVRd/hEHD7lacgqrCPS+k8g1MndzfWY=
github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk=
github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=
github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=
github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk=
github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I=
github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
github.com/docker/docker v28.5.1+incompatible h1:Bm8DchhSD2J6PsFzxC35TZo4TLGR2PdW/E69rU45NhM=
github.com/docker/docker v28.5.1+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
github.com/docker/go-connections v0.6.0 h1:LlMG9azAe1TqfR7sO+NJttz1gy6KO7VJBh+pMmjSD94=
github.com/docker/go-connections v0.6.0/go.mod h1:AahvXYshr6JgfUJGdDCs2b5EZG/vmaMAntpSFH5BFKE=
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
github.com/erikgeiser/promptkit v0.9.0 h1:3qL1mS/ntCrXdb8sTP/ka82CJ9kEQaGuYXNrYJkWYBc=
github.com/erikgeiser/promptkit v0.9.0/go.mod h1:pU9dtogSe3Jlc2AY77EP7R4WFP/vgD4v+iImC83KsCo=
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4=
github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gookit/color v1.4.2/go.mod h1:fqRyamkC1W8uxl+lxCQxOT09l/vYfZ+QeiX3rKQHCoQ=
github.com/gookit/color v1.5.0/go.mod h1:43aQb+Zerm/BWh2GnrgOQm7ffz7tvQXEKV6BFMl7wAo=
github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0=
github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 h1:8Tjv8EJ+pM1xP8mK6egEbD1OgnVTyacbefKhmbLhIhU=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2/go.mod h1:pkJQ2tZHJ0aFOVEEot6oZmaVEZcRme73eIFmhiVuRWs=
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.0.10/go.mod h1:g2LTdtYhdyuGPqyWyv7qRAmj1WBqxuObKfj5c0PQa7c=
github.com/klauspost/cpuid/v2 v2.0.12/go.mod h1:g2LTdtYhdyuGPqyWyv7qRAmj1WBqxuObKfj5c0PQa7c=
github.com/klauspost/cpuid/v2 v2.2.3 h1:sxCkb+qR91z4vsqw4vGGZlDgPz3G7gjaLyK3V8y70BU=
github.com/klauspost/cpuid/v2 v2.2.3/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/lithammer/fuzzysearch v1.1.8 h1:/HIuJnjHuXS8bKaiTMeeDlW2/AyIWk2brx1V8LFgLN4=
github.com/lithammer/fuzzysearch v1.1.8/go.mod h1:IdqeyBClc3FFqSzYq/MXESsS4S0FsZ5ajtkr5xPLts4=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4=
github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/zz4kQkprJgF2EVszyDE=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
github.com/moby/moby v28.5.2+incompatible h1:hIn6qcenb3JY1E3STwqEbBvJ8bha+u1LpqjX4CBvNCk=
github.com/moby/moby v28.5.2+incompatible/go.mod h1:fDXVQ6+S340veQPv35CzDahGBmHsiclFwfEygB/TWMc=
github.com/moby/sys/atomicwriter v0.1.0 h1:kw5D/EqkBwsBFi0ss9v1VG3wIkVhzGvLklJ+w3A14Sw=
github.com/moby/sys/atomicwriter v0.1.0/go.mod h1:Ul8oqv2ZMNHOceF643P6FKPXeCmYtlQMvpizfsSoaWs=
github.com/moby/sys/sequential v0.6.0 h1:qrx7XFUd/5DxtqcoH1h438hF5TmOvzC/lspjy7zgvCU=
github.com/moby/sys/sequential v0.6.0/go.mod h1:uyv8EUTrca5PnDsdMGXhZe6CCe8U/UiTWd+lL+7b/Ko=
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=
github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=
github.com/muesli/termenv v0.15.3-0.20240618155329-98d742f6907a h1:2MaM6YC3mGu54x+RKAA6JiFFHlHDY1UbkxqppT7wYOg=
github.com/muesli/termenv v0.15.3-0.20240618155329-98d742f6907a/go.mod h1:hxSnBBYLK21Vtq/PHd0S2FYCxBXzBua8ov5s1RobyRQ=
github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pterm/pterm v0.12.27/go.mod h1:PhQ89w4i95rhgE+xedAoqous6K9X+r6aSOI2eFF7DZI=
github.com/pterm/pterm v0.12.29/go.mod h1:WI3qxgvoQFFGKGjGnJR849gU0TsEOvKn5Q8LlY1U7lg=
github.com/pterm/pterm v0.12.30/go.mod h1:MOqLIyMOgmTDz9yorcYbcw+HsgoZo3BQfg2wtl3HEFE=
github.com/pterm/pterm v0.12.31/go.mod h1:32ZAWZVXD7ZfG0s8qqHXePte42kdz8ECtRyEejaWgXU=
github.com/pterm/pterm v0.12.33/go.mod h1:x+h2uL+n7CP/rel9+bImHD5lF3nM9vJj80k9ybiiTTE=
github.com/pterm/pterm v0.12.36/go.mod h1:NjiL09hFhT/vWjQHSj1athJpx6H8cjpHXNAK5bUw8T8=
github.com/pterm/pterm v0.12.40/go.mod h1:ffwPLwlbXxP+rxT0GsgDTzS3y3rmpAO1NMjUkGTYf8s=
github.com/pterm/pterm v0.12.79 h1:lH3yrYMhdpeqX9y5Ep1u7DejyHy7NSQg9qrBjF9dFT4=
github.com/pterm/pterm v0.12.79/go.mod h1:1v/gzOF1N0FsjbgTHZ1wVycRkKiatFvJSJC4IGaQAAo=
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ=
github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4=
github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ=
github.com/sahilm/fuzzy v0.1.1 h1:ceu5RHF8DGgoi+/dR5PsECjCDH1BE3Fnmpo7aVXOdRA=
github.com/sahilm/fuzzy v0.1.1/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=
github.com/sergi/go-diff v1.2.0 h1:XU+rvMAioB0UC3q1MFrIQy4Vo5/4VsRDQQXHsEya6xQ=
github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/skeema/knownhosts v1.3.0 h1:AM+y0rI04VksttfwjkSTNQorvGqmwATnvnAHpSgc0LY=
github.com/skeema/knownhosts v1.3.0/go.mod h1:sPINvnADmT/qYH1kfv+ePMmOBTH6Tbl7b5LvTDjFK7M=
github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8=
github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY=
github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0=
github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI=
github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778/go.mod h1:2MuV+tbUrU1zIOPMxZ5EncGwgmMJsa+9ucAQZXxsObs=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 h1:jq9TW8u3so/bN+JPT166wjOI6/vQPF6Xe7nMNIltagk=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0/go.mod h1:p8pYQP+m5XfbZm9fxtSKAbM6oIllS7s2AfxrChvc7iw=
go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8=
go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 h1:GqRJVj7UmLjCVyVJ3ZFLdPRmhDUp2zFmQe3RHIOsw24=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0/go.mod h1:ri3aaHSmCTVYu2AWv44YMauwAQc0aqI9gHKIcSbI1pU=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0 h1:aTL7F04bJHUlztTsNGJ2l+6he8c+y/b//eR0jjjemT4=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0/go.mod h1:kldtb7jDTeol0l3ewcmd8SDvx3EmIE7lyvqbasU3QC4=
go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA=
go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI=
go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E=
go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg=
go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE=
go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs=
go.opentelemetry.io/proto/otlp v1.7.1 h1:gTOMpGDb0WTBOP8JaO72iL3auEZhVmAQg4ipjOVAtj4=
go.opentelemetry.io/proto/otlp v1.7.1/go.mod h1:b2rVh6rfI/s2pHWNlB7ILJcRALpcNDzKhACevjI+ZnE=
go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI=
go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211013075003-97ac67df715c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU=
golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/genproto v0.0.0-20240213162025-012b6fc9bca9 h1:9+tzLLstTlPTRyJTh+ah5wIMsBW5c4tQwGTN3thOW9Y=
google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5 h1:BIRfGDEjiHRrk0QKZe3Xv2ieMhtgRGeLcZQ0mIVn4EY=
google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5/go.mod h1:j3QtIyytwqGr1JUDtYXwtMXWPKsEa5LtzIFN1Wn5WvE=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250825161204-c5933d9347a5 h1:eaY8u2EuxbRv7c3NiGK0/NedzVsCcV6hDuU5qPX5EGE=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250825161204-c5933d9347a5/go.mod h1:M4/wBTSeyLxupu3W3tJtOgB14jILAS/XWPSSa3TAlJc=
google.golang.org/grpc v1.75.0 h1:+TW+dqTd2Biwe6KKfhE5JpiYIBWq865PhKGSXiivqt4=
google.golang.org/grpc v1.75.0/go.mod h1:JtPAzKiq4v1xcAB2hydNlWI2RnF85XXcV0mhKXr2ecQ=
google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc=
google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q=
gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA=


================================================
FILE: main.go
================================================
/*
Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>

Licensed under the GNU GPL License, Version 3.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-3.0.en.html

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main

import "github.com/mightymoud/sidekick/cmd"

func main() {
	cmd.Execute()
}


================================================
FILE: render/tui.go
================================================
/*
Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>

Licensed under the GNU GPL License, Version 3.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-3.0.en.html

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package render

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"strings"
	"time"

	"github.com/charmbracelet/bubbles/spinner"
	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/lipgloss"
	"github.com/charmbracelet/lipgloss/tree"
)

var (
	spinnerStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("63")).MarginRight(1).MarginLeft(1)
	successStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#04B575")).MarginLeft(1)
	cancelStyle  = lipgloss.NewStyle().Foreground(lipgloss.Color("220")).Faint(true).MarginLeft(1)
	errorStyle   = lipgloss.NewStyle().Foreground(lipgloss.Color("#FF0000")).MarginLeft(1)
	pendingStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("240")).MarginLeft(1)
	allDoneStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("69")).MarginTop(1).MarginLeft(1).MarginBottom(1)
	appStyle     = lipgloss.NewStyle()
)

func (m TuiModel) Init() tea.Cmd {
	return m.Stages[m.ActiveIndex].Spinner.Tick
}

func (m TuiModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	switch msg := msg.(type) {

	case tea.KeyMsg:
		m.Quitting = true

		return m, tea.Quit

	case tea.WindowSizeMsg:
		m.ViewportHeight = msg.Height
		m.ViewportWidth = msg.Width
		return m, nil

	case LogMsg:
		logStage := m.Stages[m.ActiveIndex]
		logStage.Logs = append(logStage.Logs, msg.LogLine)
		m.Stages[m.ActiveIndex] = logStage

		return m, nil

	case ErrorMsg:
		logStage := m.Stages[m.ActiveIndex]
		logStage.HasError = true
		if msg.ErrorStr != "" {
			logStage.Logs = append(logStage.Logs, msg.ErrorStr)
		}
		m.Stages[m.ActiveIndex] = logStage

		WriteStageLogs(logStage, m.ActiveIndex)

		return m, tea.Quit

	case NextStageMsg:
		m.ActiveIndex = m.ActiveIndex + 1

		return m, m.Stages[m.ActiveIndex].Spinner.Tick

	case AllDoneMsg:
		m.AllDone = true
		m.FinalMessage = msg.Message

		return m, tea.Quit

	case spinner.TickMsg:
		var cmd tea.Cmd
		m.Stages[m.ActiveIndex].Spinner, cmd = m.Stages[m.ActiveIndex].Spinner.Update(msg)
		return m, cmd
	default:
		return m, nil
	}
}

func (m TuiModel) View() string {
	var s string
	printSlice := []string{}

	printSlice = append(printSlice, getBannerStyle(m).Render(m.BannerMsg))

	var logs string
	for _, res := range m.Stages[m.ActiveIndex].Logs {
		logs += res
	}

	for index, stage := range m.Stages {
		if !m.AllDone {
			if index < m.ActiveIndex {
				printSlice = append(printSlice, successStyle.Render("✔ "+stage.Success))
			} else if index == m.ActiveIndex {
				if !stage.HasError {
					printSlice = append(printSlice, stage.Spinner.View()+stage.Title)
				} else {
					u := tree.Root("⚠ " + stage.Title).Child(stage.Logs)
					printSlice = append(printSlice, errorStyle.Render(u.String()))
					printSlice = append(printSlice, allDoneStyle.Render("⚠️ Check sidekick.logs.txt for more details"))
				}
				if stage.HasLogs && !stage.HasError {
					var t string
					if !stage.HasError {
						l := len(stage.Logs)
						if l < 5 {
							t = getLogContainerStyle(m).Render(stage.Logs...)
						} else {
							t = getLogContainerStyle(m).Render(stage.Logs[l-5:]...)
						}
					} else {
						t = getLogContainerStyle(m).Render(stage.Logs...)
					}
					printSlice = append(printSlice, t)
				}
			} else if index > m.ActiveIndex {
				var text string
				if m.Quitting {
					text = cancelStyle.Render("CANCELLED " + stage.Title)
				} else {
					text = pendingStyle.Render("󰚭 " + stage.Title)
				}
				printSlice = append(printSlice, pendingStyle.Render(text))
			}
		} else {
			printSlice = append(printSlice, successStyle.Render("✔ "+stage.Success))
		}
	}

	if m.AllDone {
		printSlice = append(printSlice, allDoneStyle.Render(m.FinalMessage))
	}

	s += lipgloss.JoinVertical(lipgloss.Top, printSlice...)

	s += "\n"

	if m.Quitting {
		s += "\n"
	}

	return appStyle.Render(s)
}

func getLogContainerStyle(m TuiModel) lipgloss.Style {
	return lipgloss.
		NewStyle().
		Width(int(0.98 * float64(m.ViewportWidth))).
		Height(0).
		MarginLeft(int(0.01 * float64(m.ViewportWidth))).
		BorderStyle(lipgloss.RoundedBorder()).
		BorderForeground(lipgloss.Color("69")).
		Foreground(lipgloss.Color("white")).Faint(true)
}

func getBannerStyle(m TuiModel) lipgloss.Style {
	return lipgloss.NewStyle().
		Foreground(lipgloss.Color("white")).
		Background(lipgloss.Color("#414868")).
		Width(m.ViewportWidth).
		Padding(1).
		Align(lipgloss.Center).
		MarginBottom(1).
		MarginTop(1)
}

func MakeStage(title string, success string, hasLogs bool) Stage {
	s := spinner.New()
	s.Style = spinnerStyle
	s.Spinner = spinner.MiniDot

	logs := []string{}

	return Stage{
		Spinner: s,
		Title:   title,
		Success: success,
		Logs:    logs,
		HasLogs: hasLogs,
	}
}

func SendDockerBuildLogsToTUI(resBody io.ReadCloser, p *tea.Program) {
	dec := json.NewDecoder(resBody)
	for {
		var msg buildMsg
		if err := dec.Decode(&msg); err == io.EOF {
			break
		}
		// skip errors here cus shape is wront anyway -> to fix this later
		// else if err != nil {
		// fmt.Println(err)
		// }

		switch {
		case msg.Stream != "":
			p.Send(LogMsg{LogLine: msg.Stream})
		case msg.Status != "":
			if msg.ID != "" {
				// Yes yes, I'll have a closer look at this later
				// if msg.Progress != "" {
				// p.Send(render.LogMsg{LogLine: fmt.Sprintf("[%s] %s %s\n", msg.ID, msg.Status, msg.Progress)})
				// } else {
				// p.Send(LogMsg{LogLine: fmt.Sprintf("[%s] %s\n", msg.ID, msg.Status)})
				// }
			} else {
				p.Send(LogMsg{LogLine: msg.Status})
			}
		case msg.Error != "":
			p.Send(ErrorMsg{ErrorStr: msg.Error})
			time.Sleep(time.Millisecond * 50)
		}
	}
}

func SendLogsToTUI(source io.ReadCloser, p *tea.Program) {
	scanner := bufio.NewScanner(source)
	for scanner.Scan() {
		line := scanner.Text()
		if line != "\n" {
			p.Send(LogMsg{LogLine: scanner.Text() + "\n"})
			time.Sleep(time.Millisecond * 50)
		}
	}
}

// WriteStageLogs writes the logs from a specific stage to sidekick.logs.txt
func WriteStageLogs(stage Stage, stageIndex int) error {
	if len(stage.Logs) == 0 {
		return nil
	}

	file, err := os.OpenFile("sidekick.logs.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		return err
	}
	defer file.Close()

	timestamp := time.Now().Format("2006-01-02 15:04:05")
	header := fmt.Sprintf("\n=== STAGE %d ERROR LOG - %s ===\n", stageIndex+1, timestamp)
	header += fmt.Sprintf("Stage: %s\n", stage.Title)
	header += "=== LOGS START ===\n"

	if _, err := file.WriteString(header); err != nil {
		return err
	}

	for _, log := range stage.Logs {
		if _, err := file.WriteString(log); err != nil {
			return err
		}
		if !strings.HasSuffix(log, "\n") {
			if _, err := file.WriteString("\n"); err != nil {
				return err
			}
		}
	}

	footer := "=== LOGS END ===\n\n"
	if _, err := file.WriteString(footer); err != nil {
		return err
	}

	return nil
}


================================================
FILE: render/types.go
================================================
/*
Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>

Licensed under the GNU GPL License, Version 3.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-3.0.en.html

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package render

import (
	"github.com/charmbracelet/bubbles/spinner"
	tea "github.com/charmbracelet/bubbletea"
)

type LogMsg struct {
	LogLine string
}

type AllDoneMsg struct {
	Message string
}

type ErrorMsg struct {
	ErrorStr string
}
type NextStageMsg struct{}

type Stage struct {
	Title    string
	Success  string
	Spinner  spinner.Model
	Logs     []string
	HasLogs  bool
	HasError bool
}

type TuiModel struct {
	tea.Model
	ActiveIndex    int
	Stages         []Stage
	Quitting       bool
	ViewportWidth  int
	ViewportHeight int
	AllDone        bool
	BannerMsg      string
	FinalMessage   string
}

type buildMsg struct {
	Stream      string `json:"stream"`
	Status      string `json:"status"`
	ID          string `json:"id"`
	Progress    string `json:"progress"`
	ProgressMsg string `json:"progressDetail"`
	Error       string `json:"error"`
}


================================================
FILE: render/utils.go
================================================
/*
Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>

Licensed under the GNU GPL License, Version 3.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-3.0.en.html

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package render

import (
	"fmt"
	"os"
	"time"

	"github.com/charmbracelet/lipgloss"
	"github.com/charmbracelet/log"
	"github.com/erikgeiser/promptkit/textinput"
	"github.com/pterm/pterm"
	"github.com/pterm/pterm/putils"
)

func getDefaultTextInput(prompt string, defaultValue string, placeholder string) *textinput.TextInput {
	inputPrompt := fmt.Sprintf("%s: ", prompt)

	if defaultValue != "" {
		inputPrompt = fmt.Sprintf("%s \033[3m(default: %s)\033[0m: ", prompt, defaultValue)
	}

	input := textinput.New(inputPrompt)
	input.Placeholder = placeholder
	input.InitialValue = ""

	input.InputTextStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("120"))

	if defaultValue != "" {
		input.Validate = nil
	}

	return input
}

func GenerateTextQuestion(question string, defaultAnswer string, placeholder string) string {
	input := getDefaultTextInput(question, defaultAnswer, placeholder)
	userAnswer, err := input.RunPrompt()

	if err != nil {
		GetLogger(log.Options{Prefix: "Input"}).Fatalf(" %s", err)
	}

	if defaultAnswer != "" && userAnswer == "" {
		return defaultAnswer
	}

	return userAnswer
}

func GetLogger(options log.Options) *log.Logger {
	options.ReportCaller = false
	options.ReportTimestamp = true
	options.TimeFormat = time.Kitchen

	return log.NewWithOptions(os.Stderr, options)
}

func RenderSidekickBig() {
	pterm.Println()

	s, _ := pterm.DefaultBigText.WithLetters(
		putils.LettersFromStringWithStyle("Side", pterm.FgCyan.ToStyle()),
		putils.LettersFromStringWithStyle("kick", pterm.FgLightMagenta.ToStyle())).Srender()
	pterm.DefaultCenter.Println(s)

}

func RenderKeyValidation(resultLines []string, keyHash string, hostname string) {
	startColor := pterm.NewRGB(0, 255, 255)
	endColor := pterm.NewRGB(255, 0, 255)

	pterm.DefaultCenter.Print(keyHash)
	for i := 0; i < len(resultLines[1:]); i++ {
		fadeFactor := float32(i) / float32(20)
		currentColor := startColor.Fade(0, 1, fadeFactor, endColor)
		pterm.DefaultCenter.Print(currentColor.Sprint(resultLines[1:][i]))
	}
	prompt := pterm.DefaultInteractiveContinue

	pterm.DefaultCenter.Printf(pterm.FgYellow.Sprintf("This is the ASCII art and fingerprint of your VPS's public key at %s", hostname))
	pterm.DefaultCenter.Printf(pterm.FgYellow.Sprint("Please confirm you want to continue with the connection"))
	pterm.DefaultCenter.Printf(pterm.FgYellow.Sprint("Sidekick will add this host/key pair to known_hosts"))
	pterm.Println()

	prompt.DefaultText = "Would you like to proceed?"
	prompt.Options = []string{"yes", "no"}
	if result, _ := prompt.Show(); result != "yes" {
		pterm.Error.Println("In order to continue, you need to accept this.")
		os.Exit(0)
	}
}


================================================
FILE: scripts/destroy-droplets.py
================================================
# Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>
#
# Licensed under the GNU GPL License, Version 3.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.gnu.org/licenses/gpl-3.0.en.html
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Simple script to delete all droplets tagged by sidekick tag after I finish playing around.

#!/usr/bin/env python3
import os
import time
import requests

API = "https://api.digitalocean.com/v2"
DROPLETS_TAG = "sidekick"

token = os.getenv("DO_TOKEN")
if not token:
    print("❌ Please set DO_TOKEN environment variable")
    exit(1)

headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}


# destroy all droplets tagged with Sidekick
name = f"cheap-sgp1-{int(time.time())}"
r = requests.delete(f"{API}/droplets?tag_name={DROPLETS_TAG}", headers=headers)
r.raise_for_status()
# droplet_id = r.json()["droplet"]["id"]

print("✅ All droplets under Sidekick tag have been destoyed")

exit(1)


================================================
FILE: scripts/make-droplet.py
================================================
# Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>
#
# Licensed under the GNU GPL License, Version 3.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.gnu.org/licenses/gpl-3.0.en.html
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Simple script to make droplets and set them up with sidekick for my testing
# Sick of using the UI

#!/usr/bin/env python3
import os
import time
import requests
import subprocess


API = "https://api.digitalocean.com/v2"
REGION = "sgp1"
IMAGE = "ubuntu-24-04-x64"
SIZE = "s-1vcpu-2gb"
SSH_KEY_NAME = "Mac mini-new"

token = os.getenv("DO_TOKEN")
if not token:
    print("❌ Please set DO_TOKEN environment variable")
    exit(1)

headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}

# find SSH key named "Mac mini"
r = requests.get(f"{API}/account/keys", headers=headers)
r.raise_for_status()
keys = r.json()["ssh_keys"]
key = next((k for k in keys if k["name"] == SSH_KEY_NAME), None)
if not key:
    print(f"❌ No SSH key found named '{SSH_KEY_NAME}'.")
    print("Available keys:", [k["name"] for k in keys])
    exit(1)

# create droplet
name = f"cheap-sgp1-{int(time.time())}"
payload = {
    "name": name,
    "region": REGION,
    "size": SIZE,
    "image": IMAGE,
    "ssh_keys": [key["id"]],
    "backups": False,
    "ipv6": False,
    "tags": ["sidekick"],
}
r = requests.post(f"{API}/droplets", headers=headers, json=payload)
r.raise_for_status()
droplet_id = r.json()["droplet"]["id"]

print(f"✅ Droplet created (ID: {droplet_id}), waiting for IP...")

# wait for IPv4
for _ in range(120):  # ~10 minutes
    time.sleep(5)
    r = requests.get(f"{API}/droplets/{droplet_id}", headers=headers)
    droplet = r.json()["droplet"]
    networks = droplet["networks"]["v4"]
    ipv4 = next((n["ip_address"] for n in networks if n["type"] == "public"), None)
    if ipv4:
        print(ipv4)
        # print("   Giving the VPS time to boot")
        # time.sleep(10)
        # cmd = ["sidekick", "init", f"-s={ipv4}", "-e=m.mousa@hey.com", "-y"]
        # subprocess.run(cmd, check=True)
        exit(0)
    status = droplet["status"]
    print(f"   still {status}...")

print("❌ Timed out waiting for droplet IP.")
exit(1)


================================================
FILE: utils/auth.go
================================================
package utils

import (
	"errors"
	"fmt"
	"log"
	"net"
	"os"
	"os/exec"
	"os/user"
	"path"
	"strings"
	"time"

	"github.com/mightymoud/sidekick/render"
	"github.com/skeema/knownhosts"
	"golang.org/x/crypto/ssh"
	"golang.org/x/crypto/ssh/agent"
)

func getKeyFilesAuth() ([]ssh.AuthMethod, error) {
	user, err := user.Current()
	if err != nil {
		return nil, err
	}
	sshDir := path.Join(user.HomeDir, ".ssh")
	keyFiles := []string{
		"id_rsa",
		"id_ecdsa",
		"id_ed25519",
	}

	var authMethods []ssh.AuthMethod

	for _, keyFile := range keyFiles {
		keyPath := path.Join(sshDir, keyFile)
		if _, err := os.Stat(keyPath); os.IsNotExist(err) {
			continue
		}

		privateKey, err := os.ReadFile(keyPath)
		if err != nil {
			continue
		}

		signer, err := ssh.ParsePrivateKey(privateKey)
		if err != nil {
			continue
		}

		authMethods = append(authMethods, ssh.PublicKeys(signer))
	}

	return authMethods, nil
}

func inspectServerPublicKey(key ssh.PublicKey, hostname string) {
	sshKeyCmd := exec.Command("sh", "-s", "-", string(ssh.MarshalAuthorizedKey(key)))
	sshKeyCmd.Stdin = strings.NewReader(sshKeyScript)
	result, sshKeyCmdErr := sshKeyCmd.Output()
	if sshKeyCmdErr != nil {
		panic(sshKeyCmdErr)
	}
	resultLines := strings.Split(string(result), "\n")
	keyHash := resultLines[0]

	render.RenderKeyValidation(resultLines, keyHash, hostname)

}

func GetSshClient(server string, sshUser string) (*ssh.Client, error) {
	sshPort := "22"
	sshAgentSock := os.Getenv("SSH_AUTH_SOCK")
	if sshAgentSock == "" {
		log.Fatal("No SSH SOCK AVAILABLE")
		return nil, errors.New("Error happened connecting to ssh-agent")
	}

	conn, err := net.Dial("unix", sshAgentSock)
	if err != nil {
		return nil, err
	}
	defer conn.Close()

	agentClient := agent.NewClient(conn)

	// Get auth of standard keys not in agent
	authMethods, _ := getKeyFilesAuth()

	authMethods = append(authMethods, ssh.PublicKeysCallback(agentClient.Signers))

	cb := ssh.HostKeyCallback(func(hostname string, remote net.Addr, key ssh.PublicKey) error {
		currentUser, _ := user.Current()
		khPath := fmt.Sprintf("%s/.ssh/known_hosts", currentUser.HomeDir)
		kh, knErr := knownhosts.NewDB(khPath)
		if knErr != nil {
			return knErr
		}

		innerCallback := kh.HostKeyCallback()
		err := innerCallback(hostname, remote, key)
		if knownhosts.IsHostKeyChanged(err) {
			return fmt.Errorf("REMOTE HOST IDENTIFICATION HAS CHANGED for host %s! This may indicate a MitM attack.", hostname)
		} else if knownhosts.IsHostUnknown(err) {
			inspectServerPublicKey(key, hostname)
			f, ferr := os.OpenFile(khPath, os.O_APPEND|os.O_WRONLY, 0600)
			if ferr == nil {
				defer f.Close()
				ferr = knownhosts.WriteKnownHost(f, hostname, remote, key)
			} else {
				log.Printf("Failed to add host %s to known_hosts: %v\n", hostname, ferr)
			}
			return nil
		}
		return err
	})

	var client *ssh.Client

	// This error will be thrown when one method/key doesn't work
	var expectedClientErr = errors.New("ssh: handshake failed: ssh: unable to authenticate, attempted methods [none publickey], no supported methods remain")
	for _, method := range authMethods {
		config := &ssh.ClientConfig{
			User:            sshUser,
			Auth:            []ssh.AuthMethod{method},
			HostKeyCallback: cb,
			Timeout:         1 * time.Second,
		}

		workingClient, sshClientErr := ssh.Dial("tcp", fmt.Sprintf("%s:%s", server, sshPort), config)
		if sshClientErr != nil {
			if sshClientErr.Error() != expectedClientErr.Error() {
				log.Fatalf("Failed to create ssh client to the server: %v", sshClientErr)
			}
			continue
		}
		client = workingClient
		break
	}
	if client == nil {
		return nil, errors.New("Logging in failed with all available keys for the said user")
	}
	return client, nil
}

func Login(server string, user string) (*ssh.Client, error) {
	sshClient, err := GetSshClient(server, user)
	if err != nil {
		return nil, err
	}
	return sshClient, nil
}


================================================
FILE: utils/config.go
================================================
/*
Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>

Licensed under the GNU GPL License, Version 3.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-3.0.en.html

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
	"gopkg.in/yaml.v3"
)

func GetSidekickConfigFromCmdContext(cmd *cobra.Command) (*SidekickConfig, error) {
	config, ok := cmd.Context().Value("config").(*SidekickConfig)

	if !ok {
		return nil, fmt.Errorf("config not found in cmd context. This is likely a bug in the root cmd initialization.")
	}

	return config, nil
}

func (c *SidekickConfig) Save(path string) error {
	data, err := yaml.Marshal(c)
	if err != nil {
		return err
	}
	return os.WriteFile(path, data, os.ModePerm)
}

func (c *SidekickConfig) Print() error {
	data, err := yaml.Marshal(c)
	if err != nil {
		return err
	}

	_, err = os.Stdout.Write(data)
	return err
}

func (c *SidekickConfig) FindContext(name string) (SidekickContext, error) {
	for _, ctx := range c.Contexts {
		if ctx.Name == name {
			return ctx, nil
		}
	}
	return SidekickContext{}, fmt.Errorf("context '%s' not found", name)
}

func (c *SidekickConfig) FindServer(name string) (SidekickServer, error) {
	for _, s := range c.Servers {
		if s.Name == name {
			return s, nil
		}
	}
	return SidekickServer{}, fmt.Errorf("server '%s' not found", name)
}

func (c *SidekickConfig) FindServerByContext(ctxName string) (SidekickServer, error) {
	ctx, err := c.FindContext(ctxName)
	if err != nil {
		return SidekickServer{}, err
	}

	return c.FindServer(ctx.Server)
}

func (c *SidekickConfig) AddOrReplaceContext(ctx SidekickContext) {
	idx := -1
	for i, elem := range c.Contexts {
		if elem.Name == ctx.Name {
			idx = i
			break
		}
	}

	if idx == -1 {
		c.Contexts = append(c.Contexts, ctx)
	} else {
		c.Contexts[idx] = ctx
	}
}

func (c *SidekickConfig) AddOrReplaceServer(s SidekickServer) {
	idx := -1
	for i, elem := range c.Servers {
		if elem.Name == s.Name {
			idx = i
			break
		}
	}

	if idx == -1 {
		c.Servers = append(c.Servers, s)
	} else {
		c.Servers[idx] = s
	}
}


================================================
FILE: utils/docker.go
================================================
package utils

import (
	"archive/tar"
	"bytes"
	"io"
	"os"
	"path/filepath"
)

func TarDirectoryToReader(dir string) (io.Reader, error) {
	buf := new(bytes.Buffer)
	tw := tar.NewWriter(buf)
	defer tw.Close()

	filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		if err != nil || info.IsDir() {
			return err
		}
		rel, _ := filepath.Rel(dir, path)
		header, _ := tar.FileInfoHeader(info, rel)
		header.Name = rel
		tw.WriteHeader(header)
		f, _ := os.Open(path)
		io.Copy(tw, f)
		f.Close()
		return nil
	})

	return bytes.NewReader(buf.Bytes()), nil
}


================================================
FILE: utils/scripts.go
================================================
/*
Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>

Licensed under the GNU GPL License, Version 3.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-3.0.en.html

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils

var sshKeyScript = `
		publicKey=$1

		echo "$publicKey" | ssh-keygen -lvf /dev/stdin 
	`

var EnvEncryptionScript = `
	PUBKEY=$1
	ENVFILE=$2

	sops encrypt --output-type dotenv --age $PUBKEY $ENVFILE > encrypted.env
	`

var DeployAppScript = `
#!/usr/bin/env bash
set -euo pipefail

SERVICE="$service_name"
APP_PORT="$app_port"
SLEEP_AFTER_START=3
HAS_ENV=$has_env
COMPOSE_PROJECT="sidekick"

# helper for nicer logs
log() { echo "[$(date +'%T')] $*"; }


# move into service dir (assumes compose file lives in ./<service>/)
if [[ ! -d "$SERVICE" ]]; then
  log "ERROR: service directory '$SERVICE' not found."
  exit 2
fi

cd "$SERVICE"


# find the old container (oldest for this service)
old_container_id=$(docker ps -f "name=${SERVICE}" -q | tail -n1 || true)
if [[ -z "$old_container_id" ]]; then
  log "ERROR: no running containers found for service '${SERVICE}'."
  exit 3
fi

echo $old_container_id

# create a new instance by scaling up to 2 (no deps, don't recreate existing)
if [ $HAS_ENV ]; then
	sops exec-env encrypted.env "docker compose -p sidekick up -d --no-deps --scale ${SERVICE}=2 --no-recreate ${SERVICE}"
else
	docker compose -p "$COMPOSE_PROJECT" up -d --no-deps --scale "$SERVICE"=2 --no-recreate "$SERVICE"
fi

# optional small wait for the container to begin initializing
if (( SLEEP_AFTER_START > 0 )); then
  log "Sleeping $SLEEP_AFTER_START seconds for startup..."
  sleep "$SLEEP_AFTER_START"
fi

# find newest container for this service
new_container_id=$(docker ps -f "name=${SERVICE}" -q | head -n1 || true)
if [[ -z "$new_container_id" ]]; then
  log "ERROR: failed to detect new container after scaling."
  exit 4
fi

# safety: ensure new != old
if [[ "$new_container_id" == "$old_container_id" ]]; then
  log "ERROR: detected the same container as new and old ($new_container_id). Aborting."
  exit 5
fi


# get internal IP of the new container
new_container_ip=$(docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$new_container_id" || true)
if [[ -z "$new_container_ip" ]]; then
  log "ERROR: could not determine IP of new container $new_container_id"
  # clean up the new container to avoid leaving an extra one
  docker rm -f "$new_container_id" || true
  # restore scale to 1 (best effort)
  docker compose -p "$COMPOSE_PROJECT" up -d --scale "$SERVICE"=1 --no-recreate "$SERVICE" || true
  exit 6
fi


# health check (preserve your curl options)
HEALTH_URL="http://$new_container_ip:$APP_PORT/"
log "Health checking $HEALTH_URL (this may retry internally via curl)..."

if ! curl --silent --include --retry-connrefused --retry 30 --retry-delay 1 --fail "$HEALTH_URL" >/dev/null 2>&1; then
  log "ERROR: health check failed against $HEALTH_URL"
  log "Removing failed new container $new_container_id and restoring state..."
  docker rm -f "$new_container_id" || true
	if [ $HAS_ENV ]; then
		sops exec-env encrypted.env "docker compose -p ${COMPOSE_PROJECT} up -d --scale ${SERVICE}=1 --no-recreate ${SERVICE} || true"
	else 
  	docker compose -p "$COMPOSE_PROJECT" up -d --scale "$SERVICE"=1 --no-recreate "$SERVICE" || true
	fi
  exit 7
fi

log "Health check passed. Swapping containers..."

# stop & remove the old container (now safe)
docker stop "$old_container_id"
docker rm "$old_container_id"

# scale back to 1 (remove the spare)
docker compose -p "$COMPOSE_PROJECT" up -d --scale "$SERVICE"=1 --no-recreate "$SERVICE"
if [ $HAS_ENV ]; then
	sops exec-env encrypted.env "docker compose -p ${COMPOSE_PROJECT} up -d --scale ${SERVICE}=1 --no-recreate ${SERVICE}"
else
	docker compose -p "$COMPOSE_PROJECT" up -d --scale "$SERVICE"=1 --no-recreate "$SERVICE"
fi

# clean up docker system 
log "Pruning docker system"
docker system prune -f

exit 0
	`

var CheckGitTreeScript = `
	if [[ -z $(git status -s) ]]
	then
	  echo "all good"
	else
	  echo "tree is dirty, please commit changes before running this"
	  exit
	fi
	`

var SetupStageScript = `
#!/usr/bin/env bash
set -e

wait_for_locks() {
    echo "Waiting for apt/dpkg locks..."
    while fuser /var/lib/dpkg/lock >/dev/null 2>&1 \
       || fuser /var/lib/dpkg/lock-frontend >/dev/null 2>&1 \
       || fuser /var/lib/apt/lists/lock >/dev/null 2>&1; do
        sleep 1
    done
}

echo "\033[0;32mUpdating SSH config...\033[0m"
ex -s -c 'g/PermitRootLogin/d' -c 'g/AcceptEnv SOPS_*/d' -c 'wq' /etc/ssh/sshd_config
echo 'AcceptEnv SOPS_*' | tee -a /etc/ssh/sshd_config > /dev/null
echo 'PermitRootLogin no' | tee -a /etc/ssh/sshd_config > /dev/null
systemctl restart ssh

echo "\033[0;32mUpdating Packages...\033[0m"
wait_for_locks
sudo apt-get update -y

wait_for_locks
sudo apt-get upgrade -y

echo "\033[0;32mInstalling Necessities ...\033[0m"
wait_for_locks
sudo apt-get install -y age ca-certificates curl vim

echo "\033[0;32mInstalling SOPS...\033[0m"
curl -sLO https://github.com/getsops/sops/releases/download/v3.9.0/sops-v3.9.0.linux.amd64
sudo mv sops-v3.9.0.linux.amd64 /usr/local/bin/sops
sudo chmod +x /usr/local/bin/sops
`

var TraefikDockerComposeFile = `
services:
  traefik-service:
    image: traefik:v3.6.1
    command:
      - --api.insecure=false
      - --entrypoints.web.address=:80
      - --entrypoints.web.http.redirections.entryPoint.to=websecure
      - --entrypoints.web.http.redirections.entryPoint.scheme=https
      - --entrypoints.websecure.address=:443
      - --entrypoints.websecure.http.tls.certresolver=default
      - --providers.docker.exposedbydefault=false
      - --certificatesresolvers.default.acme.email=$EMAIL
      - --certificatesresolvers.default.acme.storage=/ssl-certs/acme.json
      - --certificatesresolvers.default.acme.httpchallenge.entrypoint=web
    ports:
      - "80:80"
      - "443:443"
      # The Web UI (enabled by --api.insecure=true)
      # - "8080:8080"
    volumes:
      # So that Traefik can listen to the Docker events
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - ./traefik/ssl/:/ssl-certs/
    networks:
      - sidekick

networks:
  sidekick:
    external: true
`


================================================
FILE: utils/spinner.go
================================================
/*
Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>

Licensed under the GNU GPL License, Version 3.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-3.0.en.html

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils

import (
	"github.com/pterm/pterm"
)

var stagedSpinner = pterm.DefaultSpinner

func GetSpinner() pterm.SpinnerPrinter {
	stagedSpinner.Sequence = []string{"."}
	stagedSpinner.ShowTimer = false
	return stagedSpinner
}


================================================
FILE: utils/stages.go
================================================
/*
Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>

Licensed under the GNU GPL License, Version 3.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-3.0.en.html

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils

import (
	"encoding/base64"
	"fmt"
	"strings"
)

var UsersetupStage = CommandsStage{
	SpinnerSuccessMessage: "New user created successfully",
	SpinnerFailMessage:    "Error creating a new user for the machine",
	Commands: []string{
		"sudo useradd -m -s /bin/bash -G sudo sidekick",
		`echo "sidekick ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers.d/sidekick`,
		"mkdir -p /home/sidekick/.ssh/",
		"sudo cat /root/.ssh/authorized_keys | sudo tee -a /home/sidekick/.ssh/authorized_keys",
		"sudo chown sidekick:sidekick /home/sidekick/.ssh/authorized_keys",
		"sudo chmod 600 /home/sidekick/.ssh/authorized_keys",
	},
}

var SetupStage = CommandsStage{
	SpinnerSuccessMessage: "VPS updated and setup successfully",
	SpinnerFailMessage:    "Error happened running basic setup commands",
	Commands: []string{
		fmt.Sprintf("echo '%s' | base64 -d > setup.sh", base64.StdEncoding.EncodeToString([]byte(SetupStageScript))),
		"chmod +x ./setup.sh",
		"sudo ./setup.sh",
		"rm ./setup.sh",
	},
}

var DockerStage = CommandsStage{
	SpinnerSuccessMessage: "Docker setup successfully",
	SpinnerFailMessage:    "Error happened during setting up docker",
	Commands: []string{
		"sudo apt-get update -y",
		"sudo install -m 0755 -d /etc/apt/keyrings",
		"sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc",
		"sudo chmod a+r /etc/apt/keyrings/docker.asc",
		`echo \
		"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
		$(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
		sudo tee /etc/apt/sources.list.d/docker.list > /dev/null`,
		"sudo apt-get update -y",
		"sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin -y",
		"sudo usermod -aG docker sidekick",
	},
}

func GetTraefikStage(email string) CommandsStage {
	return CommandsStage{
		SpinnerSuccessMessage: "Successfully setup Traefik",
		SpinnerFailMessage:    "Something went wrong setting up Traefik on your VPS",
		Commands: []string{
			"mkdir traefik",
			fmt.Sprintf("echo '%s' > ./traefik/docker-compose.yml", strings.Replace(TraefikDockerComposeFile, "$EMAIL", email, 1)),
			"mkdir -p ./traefik/ssl-certs/",
			"touch ./traefik/ssl-certs/acme.json",
			"chmod 600 ./traefik/ssl-certs/acme.json",
			"sudo docker network create sidekick",
			"cd traefik && sudo docker compose -p sidekick up -d",
		},
	}
}


================================================
FILE: utils/types.go
================================================
/*
Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>

Licensed under the GNU GPL License, Version 3.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-3.0.en.html

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils

type DependsOn struct {
	Condition string `yaml:"condition"`
}

type Healthcheck struct {
	Test     []string `yaml:"test"`
	Interval string   `yaml:"interval"`
	Timeout  string   `yaml:"timeout"`
	Retries  int      `yaml:"retries"`
}

type DockerService struct {
	Image       string               `yaml:"image"`
	Command     string               `yaml:"command,omitempty"`
	Restart     string               `yaml:"restart,omitempty"`
	Ports       []string             `yaml:"ports,omitempty"`
	Volumes     []string             `yaml:"volumes,omitempty"`
	Labels      []string             `yaml:"labels,omitempty"`
	Networks    []string             `yaml:"networks,omitempty"`
	Environment []string             `yaml:"environment,omitempty"`
	DependsOn   map[string]DependsOn `yaml:"depends_on,omitempty"`
	HealthCheck Healthcheck          `yaml:"healthcheck,omitempty"`
	EntryPoint  []string             `yaml:"entrypoint,omitempty"`
}

type DockerNetwork struct {
	External bool `yaml:"external"`
}

type DockerComposeFile struct {
	Services map[string]DockerService `yaml:"services"`
	Networks map[string]DockerNetwork `yaml:"networks,omitempty"`
	Volumes  map[string]DockerVolume  `yaml:"volumes,omitempty"`
}

type DockerVolume struct {
	Driver string `yaml:"driver,omitempty"`
}
type SidekickAppEnvConfig struct {
	File string `yaml:"file"`
	Hash string `yaml:"hash"`
}

type SidekickPreview struct {
	Url       string `yaml:"url"`
	Image     string `yaml:"image"`
	CreatedAt string `yaml:"createdAt"`
}

type SidekickAppDatabaseBackupConfig struct {
	Target       string `yaml:"target"`
	BucketName   string `yaml:"bucketName"`
	BucketPath   string `yaml:"path"`
	BucketRegion string `yaml:"region"`
	S3Endpoint   string `yaml:"s3Endpoint"`
}

type SidekickAppDatabaseConfig struct {
	Type   string                          `yaml:"type"`
	DbName string                          `yaml:"databaseName"`
	Backup SidekickAppDatabaseBackupConfig `yaml:"backup,omitempty"`
}

type SidekickAppConfig struct {
	Name           string                     `yaml:"name"`
	Version        string                     `yaml:"version"`
	Image          string                     `yaml:"image"`
	Url            string                     `yaml:"url"`
	Port           uint64                     `yaml:"port"`
	CreatedAt      string                     `yaml:"createdAt"`
	Env            SidekickAppEnvConfig       `yaml:"env,omitempty"`
	DatabaseConfig SidekickAppDatabaseConfig  `yaml:"database,omitempty"`
	PreviewEnvs    map[string]SidekickPreview `yaml:"previewEnvs,omitempty"`
	Server         string                     `yaml:"server"`
}
type EnvVar map[string]string

type SidekickConfig struct {
	Version        string            `yaml:"version"`
	Servers        []SidekickServer  `yaml:"servers"`
	Contexts       []SidekickContext `yaml:"contexts"`
	CurrentContext string            `yaml:"current-context"`
}

type SidekickServer struct {
	Name       string `yaml:"name"`
	Address    string `yaml:"serveraddress"`
	Distro     string `yaml:"distro"`
	PlatformId string `yaml:"platformid"`
	CertEmail  string `yaml:"certemail"`
	PublicKey  string `yaml:"publickey"`
	SecretKey  string `yaml:"secretkey"`
}

type SidekickContext struct {
	Name   string `yaml:"name"`
	Server string `yaml:"server"`
}


================================================
FILE: utils/utils.go
================================================
/*
Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>

Licensed under the GNU GPL License, Version 3.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-3.0.en.html

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils

import (
	"bufio"
	"crypto/md5"
	"errors"
	"fmt"
	"os"
	"os/exec"
	"regexp"
	"strings"
	"time"

	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/log"
	"github.com/joho/godotenv"
	"github.com/mightymoud/sidekick/render"
	"github.com/pterm/pterm"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"golang.org/x/crypto/ssh"
	"gopkg.in/yaml.v3"
)

type CommandsStage struct {
	Commands              []string
	SpinnerSuccessMessage string
	SpinnerFailMessage    string
}

func RunCommand(client *ssh.Client, cmd string) (chan string, chan string, error) {
	session, err := client.NewSession()
	errChannel := make(chan string)
	stdOutChannel := make(chan string)
	if err != nil {
		log.Fatalf("Failed to create session: %s", err)
	}
	defer session.Close()
	// Need to hook into the pipe of output coming from that session
	stdoutReader, err := session.StdoutPipe()
	if err != nil {
		return nil, nil, fmt.Errorf("error getting stdout reader: %s", err)
	}
	stderrReader, err := session.StderrPipe()
	if err != nil {
		return nil, nil, fmt.Errorf("error getting stderr reader: %s", err)
	}

	// make a scanner of that reader that will read as we get new stuff
	stdoutScanner := bufio.NewScanner(stdoutReader)
	stderrScanner := bufio.NewScanner(stderrReader)

	// start separate go routines to read from the pipes and print out
	go func() {
		for stdoutScanner.Scan() {
			stdOutChannel <- stdoutScanner.Text()
			// fmt.Printf("\033[34m[STDOUT]\033[0m %s\n", stdoutScanner.Text())
		}
	}()

	go func() {
		for stderrScanner.Scan() {
			errChannel <- stderrScanner.Text()
			// fmt.Printf("\n\033[31m[STDERR]\033[0m %s\n", stderrScanner.Text())
		}
	}()

	if err := session.Run(cmd); err != nil {
		defer session.Close()
		errString := <-errChannel
		return nil, nil, fmt.Errorf("error running command - %s: - %s", cmd, errString)
	}

	time.Sleep(time.Millisecond * 500)
	return stdOutChannel, errChannel, nil
}

func RunCommandWithTUIHook(client *ssh.Client, cmd string, p *tea.Program, envVars ...EnvVar) {
	session, err := client.NewSession()
	if err != nil {
		log.Fatalf("Failed to create session: %s", err)
	}
	defer session.Close()

	for _, env := range envVars {
		for key, value := range env {
			err := session.Setenv(key, value)
			if err != nil {
				p.Send(render.ErrorMsg{ErrorStr: fmt.Sprintf("error is:%s", err)})
			}
		}
	}

	stdoutReader, err := session.StdoutPipe()
	if err != nil {
		p.Send(render.ErrorMsg{ErrorStr: fmt.Sprintf("error running command - %s: - %s", cmd, err) + err.Error()})
	}
	stderrReader, err := session.StderrPipe()
	if err != nil {
		p.Send(render.ErrorMsg{ErrorStr: fmt.Sprintf("error running command - %s: - %s", cmd, err) + err.Error()})
	}

	stdoutScanner := bufio.NewScanner(stdoutReader)
	stderrScanner := bufio.NewScanner(stderrReader)

	if err := session.Start(cmd); err != nil {
		time.Sleep(time.Millisecond * 100)
		p.Send(render.ErrorMsg{ErrorStr: fmt.Sprintf("error running command - %s: - %s", cmd, err) + err.Error()})
	}

	for stdoutScanner.Scan() {
		p.Send(render.LogMsg{LogLine: stdoutScanner.Text() + "\n"})
		time.Sleep(time.Millisecond * 50)
	}

	for stderrScanner.Scan() {
		p.Send(render.LogMsg{LogLine: stderrScanner.Text() + "\n"})
		time.Sleep(time.Millisecond * 50)
	}

	if err := session.Wait(); err != nil {
		if len(cmd) >= 80 {
			p.Send(render.ErrorMsg{ErrorStr: fmt.Sprintf("Failed with following error - %s", err) + err.Error()})
		} else {
			p.Send(render.ErrorMsg{ErrorStr: fmt.Sprintf("error running command - %s: - %s", cmd, err) + err.Error()})
		}
	}
}

func RunCommands(client *ssh.Client, commands []string) error {
	for _, cmd := range commands {
		_, _, err := RunCommand(client, cmd)
		if err != nil {
			return err
		}

	}
	return nil
}

func RunCommandsWithTUIHook(client *ssh.Client, commands []string, p *tea.Program) error {
	for _, cmd := range commands {
		RunCommandWithTUIHook(client, cmd, p)
	}
	return nil
}

func RunStage(client *ssh.Client, stage CommandsStage) error {
	if err := RunCommands(client, stage.Commands); err != nil {
		return err
	}
	return nil
}

func IsValidIPAddress(ip string) bool {
	const ipPattern = `\b(?:\d{1,3}\.){3}\d{1,3}\b`

	re := regexp.MustCompile(ipPattern)

	return re.MatchString(ip)
}

func FileExists(filename string) bool {
	_, err := os.Stat(filename)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	return false
}

func ViperInit() error {
	home, err := os.UserHomeDir()
	cobra.CheckErr(err)

	configPath := fmt.Sprintf("%s/.config/sidekick", home)

	viper.AddConfigPath(configPath)
	viper.SetConfigType("yaml")
	viper.SetConfigName("default")
	err = viper.ReadInConfig()
	if err != nil {
		return err
	}
	return nil
}

func LoadAppConfig() (SidekickAppConfig, error) {
	if !FileExists("./sidekick.yml") {
		return SidekickAppConfig{}, errors.New("Sidekick app config not found. Please run sidekick launch first")
	}
	appConfigFile := SidekickAppConfig{}
	content, err := os.ReadFile("./sidekick.yml")
	if err != nil {
		pterm.Error.Println("Unable to process your project config")
		os.Exit(1)
	}
	if err := yaml.Unmarshal(content, &appConfigFile); err != nil {
		panic(err)
	}

	return appConfigFile, nil
}

func HandleEnvFile(envFileName string, dockerEnvProperty *[]string, envFileChecksum *string, publicKey string) error {
	envFile, envFileErr := os.Open(fmt.Sprintf("./%s", envFileName))
	if envFileErr != nil {
		return envFileErr
	}
	envMap, envParseErr := godotenv.Parse(envFile)
	if envParseErr != nil {
		return envParseErr
	}

	for key := range envMap {
		if strings.HasPrefix(key, "_") {
			continue
		}
		*dockerEnvProperty = append(*dockerEnvProperty, fmt.Sprintf("%s=${%s}", key, key))
	}
	// calculate and store the hash of env file to re-encrypt later on when changed
	envFileContent, _ := godotenv.Marshal(envMap)
	*envFileChecksum = fmt.Sprintf("%x", md5.Sum([]byte(envFileContent)))
	envCmd := exec.Command("sops",
		"encrypt",
		"--output-type", "dotenv",
		"--age", publicKey,
		fmt.Sprintf("./%s", envFileName),
	)
	outfile, err := os.Create("encrypted.env")
	if err != nil {
		return err
	}
	defer outfile.Close()
	envCmd.Stdout = outfile
	if envCmdErr := envCmd.Run(); envCmdErr != nil {
		return envCmdErr
	}
	return nil
}

func WriteEnvFile(filename string, env map[string]string) error {
	f, err := os.Open(filename)
	if err != nil {
		return fmt.Errorf("error openign file: %w", err)
	}
	defer f.Close()

	for key, value := range env {
		// Check if the value contains spaces or special characters
		// and quote it if needed.  This is important for robustness.
		if strings.ContainsAny(value, " \t\n\r\"") {
			value = fmt.Sprintf("\"%s\"", strings.ReplaceAll(value, "\"", "\\\"")) // Escape inner quotes
		}
		if _, err := f.WriteString(fmt.Sprintf("%s=%s\n", key, value)); err != nil {
			return fmt.Errorf("error writing to file: %w", err)
		}
	}
	return nil
}


================================================
FILE: utils/utils_test.go
================================================
package utils_test

import (
	"crypto/md5"
	"fmt"
	"os"
	"testing"

	"github.com/joho/godotenv"
	"github.com/mightymoud/sidekick/utils"
	"github.com/stretchr/testify/assert"
)

func TestHandleEnvFile(t *testing.T) {
	envFileName := "test.env"
	dockerEnvProperty := []string{}
	var envFileChecksum string

	envContent := "KEY1=value1\nKEY2=value2"

	err := os.WriteFile(envFileName, []byte(envContent), 0644)
	assert.NoError(t, err)
	defer os.Remove(envFileName)
	defer os.Remove("encrypted.env")
	envFile, envFileErr := os.Open(fmt.Sprintf("./%s", envFileName))
	assert.NoError(t, envFileErr)

	envMap, envParseErr := godotenv.Parse(envFile)
	assert.NoError(t, envParseErr)
	envFileContent, envMarshalErr := godotenv.Marshal(envMap)
	assert.NoError(t, envMarshalErr)

	pub := "age1lgjx644dkpj2nas84pfe4dsd96tph8yxhgf6zfh58kqw06qycavsz00rzm"
	err = utils.HandleEnvFile(envFileName, &dockerEnvProperty, &envFileChecksum, pub)
	assert.NoError(t, err)

	assert.Contains(t, dockerEnvProperty, "KEY2=${KEY2}")
	assert.Contains(t, dockerEnvProperty, "KEY1=${KEY1}")

	expectedChecksum := fmt.Sprintf("%x", md5.Sum([]byte(envFileContent)))
	assert.Equal(t, expectedChecksum, envFileChecksum)
}
func TestLoadAppConfig(t *testing.T) {
	configContent := `
name: test
version: V1
image: ""
url: MOCK_URL
port: 3000
createdAt: Mon Nov 11 21:42:50 KST 2024
`
	err := os.WriteFile("sidekick.yml", []byte(configContent), 0644)
	assert.NoError(t, err)
	defer os.Remove("sidekick.yml")

	appConfig, err := utils.LoadAppConfig()
	assert.NoError(t, err)

	assert.Equal(t, "test", appConfig.Name)
	assert.Equal(t, "V1", appConfig.Version)
	assert.Equal(t, "MOCK_URL", appConfig.Url)
}

func TestLoadAppConfig_FileNotFound(t *testing.T) {
	os.Remove("sidekick.yml")

	_, err := utils.LoadAppConfig()
	assert.Error(t, err)
	assert.Equal(t, "Sidekick app config not found. Please run sidekick launch first", err.Error())
}
Download .txt
gitextract_0fuar_rb/

├── .gitignore
├── .goreleaser.yaml
├── LICENSE
├── README.md
├── cmd/
│   ├── config/
│   │   └── config.go
│   ├── deploy/
│   │   └── deploy.go
│   ├── destroy.go
│   ├── initialize/
│   │   └── initialize.go
│   ├── launch/
│   │   └── launch.go
│   ├── preview/
│   │   ├── list/
│   │   │   └── list.go
│   │   ├── preview.go
│   │   └── remove/
│   │       └── remove.go
│   └── root.go
├── go.mod
├── go.sum
├── main.go
├── render/
│   ├── tui.go
│   ├── types.go
│   └── utils.go
├── scripts/
│   ├── destroy-droplets.py
│   └── make-droplet.py
└── utils/
    ├── auth.go
    ├── config.go
    ├── docker.go
    ├── scripts.go
    ├── spinner.go
    ├── stages.go
    ├── types.go
    ├── utils.go
    └── utils_test.go
Download .txt
SYMBOL INDEX (97 symbols across 20 files)

FILE: cmd/config/config.go
  function init (line 94) | func init() {

FILE: cmd/deploy/deploy.go
  function prelude (line 39) | func prelude(config *utils.SidekickConfig) (utils.SidekickAppConfig, uti...
  function stage1Login (line 88) | func stage1Login(server *utils.SidekickServer) (*ssh.Client, error) {
  function stage2EnvFile (line 93) | func stage2EnvFile(appConfig utils.SidekickAppConfig, p *tea.Program, se...
  function stage3BuildDockerImage (line 124) | func stage3BuildDockerImage(appConfig utils.SidekickAppConfig, p *tea.Pr...
  function stage4SaveDockerImage (line 137) | func stage4SaveDockerImage(appConfig utils.SidekickAppConfig, p *tea.Pro...
  function stage5MoveDockerImage (line 149) | func stage5MoveDockerImage(appConfig utils.SidekickAppConfig, p *tea.Pro...
  function stage6Deploy (line 163) | func stage6Deploy(sshClient *ssh.Client, appConfig utils.SidekickAppConf...

FILE: cmd/destroy.go
  function init (line 33) | func init() {

FILE: cmd/initialize/initialize.go
  function stage1LocalReqs (line 34) | func stage1LocalReqs() error {
  function stage2Login (line 50) | func stage2Login(server string) (*ssh.Client, string, error) {
  function stage3UserSetup (line 61) | func stage3UserSetup(client *ssh.Client, loggedInUser string) error {
  function stage4VPSSetup (line 81) | func stage4VPSSetup(client *ssh.Client, p *tea.Program, server *utils.Si...
  function stage5Docker (line 120) | func stage5Docker(client *ssh.Client, p *tea.Program) error {
  function stage6Traefik (line 138) | func stage6Traefik(client *ssh.Client, email string, p *tea.Program) err...
  function init (line 302) | func init() {

FILE: cmd/launch/launch.go
  function getDockerClient (line 41) | func getDockerClient() (*client.Client, error) {
  function prelude (line 56) | func prelude(server *utils.SidekickServer) string {
  function stage1 (line 90) | func stage1(server *utils.SidekickServer) (*ssh.Client, error) {
  function stage2 (line 95) | func stage2(appName string, p *tea.Program, server *utils.SidekickServer...
  function stage3 (line 121) | func stage3(appName string, p *tea.Program) error {
  function stage4 (line 143) | func stage4(sshClient *ssh.Client, appName string, p *tea.Program, serve...
  function stage5 (line 170) | func stage5(sshClient *ssh.Client, appName string, appPort string, appDo...

FILE: cmd/preview/preview.go
  function init (line 268) | func init() {

FILE: cmd/preview/remove/remove.go
  function deletePreviewEnv (line 108) | func deletePreviewEnv(hash string) {

FILE: cmd/root.go
  function Execute (line 46) | func Execute() {
  function init (line 53) | func init() {
  function initConfig (line 72) | func initConfig(cmd *cobra.Command) {
  function requireConfigFile (line 106) | func requireConfigFile(cmd *cobra.Command) bool {
  function shouldSkipConfigVersionCheck (line 122) | func shouldSkipConfigVersionCheck(cmd *cobra.Command) bool {

FILE: main.go
  function main (line 19) | func main() {

FILE: render/tui.go
  method Init (line 42) | func (m TuiModel) Init() tea.Cmd {
  method Update (line 46) | func (m TuiModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
  method View (line 98) | func (m TuiModel) View() string {
  function getLogContainerStyle (line 164) | func getLogContainerStyle(m TuiModel) lipgloss.Style {
  function getBannerStyle (line 175) | func getBannerStyle(m TuiModel) lipgloss.Style {
  function MakeStage (line 186) | func MakeStage(title string, success string, hasLogs bool) Stage {
  function SendDockerBuildLogsToTUI (line 202) | func SendDockerBuildLogsToTUI(resBody io.ReadCloser, p *tea.Program) {
  function SendLogsToTUI (line 235) | func SendLogsToTUI(source io.ReadCloser, p *tea.Program) {
  function WriteStageLogs (line 247) | func WriteStageLogs(stage Stage, stageIndex int) error {

FILE: render/types.go
  type LogMsg (line 22) | type LogMsg struct
  type AllDoneMsg (line 26) | type AllDoneMsg struct
  type ErrorMsg (line 30) | type ErrorMsg struct
  type NextStageMsg (line 33) | type NextStageMsg struct
  type Stage (line 35) | type Stage struct
  type TuiModel (line 44) | type TuiModel struct
  type buildMsg (line 56) | type buildMsg struct

FILE: render/utils.go
  function getDefaultTextInput (line 29) | func getDefaultTextInput(prompt string, defaultValue string, placeholder...
  function GenerateTextQuestion (line 49) | func GenerateTextQuestion(question string, defaultAnswer string, placeho...
  function GetLogger (line 64) | func GetLogger(options log.Options) *log.Logger {
  function RenderSidekickBig (line 72) | func RenderSidekickBig() {
  function RenderKeyValidation (line 82) | func RenderKeyValidation(resultLines []string, keyHash string, hostname ...

FILE: utils/auth.go
  function getKeyFilesAuth (line 21) | func getKeyFilesAuth() ([]ssh.AuthMethod, error) {
  function inspectServerPublicKey (line 57) | func inspectServerPublicKey(key ssh.PublicKey, hostname string) {
  function GetSshClient (line 71) | func GetSshClient(server string, sshUser string) (*ssh.Client, error) {
  function Login (line 146) | func Login(server string, user string) (*ssh.Client, error) {

FILE: utils/config.go
  function GetSidekickConfigFromCmdContext (line 25) | func GetSidekickConfigFromCmdContext(cmd *cobra.Command) (*SidekickConfi...
  method Save (line 35) | func (c *SidekickConfig) Save(path string) error {
  method Print (line 43) | func (c *SidekickConfig) Print() error {
  method FindContext (line 53) | func (c *SidekickConfig) FindContext(name string) (SidekickContext, erro...
  method FindServer (line 62) | func (c *SidekickConfig) FindServer(name string) (SidekickServer, error) {
  method FindServerByContext (line 71) | func (c *SidekickConfig) FindServerByContext(ctxName string) (SidekickSe...
  method AddOrReplaceContext (line 80) | func (c *SidekickConfig) AddOrReplaceContext(ctx SidekickContext) {
  method AddOrReplaceServer (line 96) | func (c *SidekickConfig) AddOrReplaceServer(s SidekickServer) {

FILE: utils/docker.go
  function TarDirectoryToReader (line 11) | func TarDirectoryToReader(dir string) (io.Reader, error) {

FILE: utils/spinner.go
  function GetSpinner (line 23) | func GetSpinner() pterm.SpinnerPrinter {

FILE: utils/stages.go
  function GetTraefikStage (line 65) | func GetTraefikStage(email string) CommandsStage {

FILE: utils/types.go
  type DependsOn (line 17) | type DependsOn struct
  type Healthcheck (line 21) | type Healthcheck struct
  type DockerService (line 28) | type DockerService struct
  type DockerNetwork (line 42) | type DockerNetwork struct
  type DockerComposeFile (line 46) | type DockerComposeFile struct
  type DockerVolume (line 52) | type DockerVolume struct
  type SidekickAppEnvConfig (line 55) | type SidekickAppEnvConfig struct
  type SidekickPreview (line 60) | type SidekickPreview struct
  type SidekickAppDatabaseBackupConfig (line 66) | type SidekickAppDatabaseBackupConfig struct
  type SidekickAppDatabaseConfig (line 74) | type SidekickAppDatabaseConfig struct
  type SidekickAppConfig (line 80) | type SidekickAppConfig struct
  type EnvVar (line 92) | type EnvVar
  type SidekickConfig (line 94) | type SidekickConfig struct
  type SidekickServer (line 101) | type SidekickServer struct
  type SidekickContext (line 111) | type SidekickContext struct

FILE: utils/utils.go
  type CommandsStage (line 39) | type CommandsStage struct
  function RunCommand (line 45) | func RunCommand(client *ssh.Client, cmd string) (chan string, chan strin...
  function RunCommandWithTUIHook (line 92) | func RunCommandWithTUIHook(client *ssh.Client, cmd string, p *tea.Progra...
  function RunCommands (line 144) | func RunCommands(client *ssh.Client, commands []string) error {
  function RunCommandsWithTUIHook (line 155) | func RunCommandsWithTUIHook(client *ssh.Client, commands []string, p *te...
  function RunStage (line 162) | func RunStage(client *ssh.Client, stage CommandsStage) error {
  function IsValidIPAddress (line 169) | func IsValidIPAddress(ip string) bool {
  function FileExists (line 177) | func FileExists(filename string) bool {
  function ViperInit (line 188) | func ViperInit() error {
  function LoadAppConfig (line 204) | func LoadAppConfig() (SidekickAppConfig, error) {
  function HandleEnvFile (line 221) | func HandleEnvFile(envFileName string, dockerEnvProperty *[]string, envF...
  function WriteEnvFile (line 258) | func WriteEnvFile(filename string, env map[string]string) error {

FILE: utils/utils_test.go
  function TestHandleEnvFile (line 14) | func TestHandleEnvFile(t *testing.T) {
  function TestLoadAppConfig (line 43) | func TestLoadAppConfig(t *testing.T) {
  function TestLoadAppConfig_FileNotFound (line 64) | func TestLoadAppConfig_FileNotFound(t *testing.T) {
Condensed preview — 30 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (201K chars).
[
  {
    "path": ".gitignore",
    "chars": 17,
    "preview": "\ndist/\n.DS_Store\n"
  },
  {
    "path": ".goreleaser.yaml",
    "chars": 1224,
    "preview": "# This is an example .goreleaser.yml file with some sensible defaults.\n# Make sure to check the documentation at https:/"
  },
  {
    "path": "LICENSE",
    "chars": 35133,
    "preview": "    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundat"
  },
  {
    "path": "README.md",
    "chars": 8577,
    "preview": "<div align=\"center\">\n  <div>\n    <img width=\"110px\" src=\"https://emoji.aranja.com/static/emoji-data/img-apple-160/1f91c-"
  },
  {
    "path": "cmd/config/config.go",
    "chars": 2565,
    "preview": "/*\nCopyright © 2024 Mahmoud Mousa <m.mousa@hey.com>\n\nLicensed under the GNU GPL License, Version 3.0 (the \"License\");\nyo"
  },
  {
    "path": "cmd/deploy/deploy.go",
    "chars": 10953,
    "preview": "/*\nCopyright © 2024 Mahmoud Mousa <m.mousa@hey.com>\n\nLicensed under the GNU GPL License, Version 3.0 (the \"License\");\nyo"
  },
  {
    "path": "cmd/destroy.go",
    "chars": 1506,
    "preview": "/*\nCopyright © 2024 Mahmoud Mousa <m.mousa@hey.com>\n\nLicensed under the GNU GPL License, Version 3.0 (the \"License\");\nyo"
  },
  {
    "path": "cmd/initialize/initialize.go",
    "chars": 9425,
    "preview": "/*\nCopyright © 2024 Mahmoud Mousa <m.mousa@hey.com>\n\nLicensed under the GNU GPL License, Version 3.0 (the \"License\");\nyo"
  },
  {
    "path": "cmd/launch/launch.go",
    "chars": 13030,
    "preview": "/*\nCopyright © 2024 Mahmoud Mousa <m.mousa@hey.com>\n\nLicensed under the GNU GPL License, Version 3.0 (the \"License\");\nyo"
  },
  {
    "path": "cmd/preview/list/list.go",
    "chars": 2428,
    "preview": "/*\nCopyright © 2024 Mahmoud Mousa <m.mousa@hey.com>\n\nLicensed under the GNU GPL License, Version 3.0 (the \"License\");\nyo"
  },
  {
    "path": "cmd/preview/preview.go",
    "chars": 10130,
    "preview": "/*\nCopyright © 2024 Mahmoud Mousa <m.mousa@hey.com>\n\nLicensed under the GNU GPL License, Version 3.0 (the \"License\");\nyo"
  },
  {
    "path": "cmd/preview/remove/remove.go",
    "chars": 4344,
    "preview": "/*\nCopyright © 2024 Mahmoud Mousa <m.mousa@hey.com>\n\nLicensed under the GNU GPL License, Version 3.0 (the \"License\");\nyo"
  },
  {
    "path": "cmd/root.go",
    "chars": 3537,
    "preview": "/*\nCopyright © 2024 Mahmoud Mousa <m.mousa@hey.com>\n\nLicensed under the GNU GPL License, Version 3.0 (the \"License\");\nyo"
  },
  {
    "path": "go.mod",
    "chars": 4839,
    "preview": "module github.com/mightymoud/sidekick\n\ngo 1.24.0\n\ntoolchain go1.24.5\n\nrequire (\n\tgithub.com/charmbracelet/bubbles v0.21."
  },
  {
    "path": "go.sum",
    "chars": 33441,
    "preview": "atomicgo.dev/assert v0.0.2 h1:FiKeMiZSgRrZsPo9qn/7vmr7mCsh5SZyXY4YGYiYwrg=\natomicgo.dev/assert v0.0.2/go.mod h1:ut4NcI3Q"
  },
  {
    "path": "main.go",
    "chars": 668,
    "preview": "/*\nCopyright © 2024 Mahmoud Mousa <m.mousa@hey.com>\n\nLicensed under the GNU GPL License, Version 3.0 (the \"License\");\nyo"
  },
  {
    "path": "render/tui.go",
    "chars": 7337,
    "preview": "/*\nCopyright © 2024 Mahmoud Mousa <m.mousa@hey.com>\n\nLicensed under the GNU GPL License, Version 3.0 (the \"License\");\nyo"
  },
  {
    "path": "render/types.go",
    "chars": 1431,
    "preview": "/*\nCopyright © 2024 Mahmoud Mousa <m.mousa@hey.com>\n\nLicensed under the GNU GPL License, Version 3.0 (the \"License\");\nyo"
  },
  {
    "path": "render/utils.go",
    "chars": 3228,
    "preview": "/*\nCopyright © 2024 Mahmoud Mousa <m.mousa@hey.com>\n\nLicensed under the GNU GPL License, Version 3.0 (the \"License\");\nyo"
  },
  {
    "path": "scripts/destroy-droplets.py",
    "chars": 1314,
    "preview": "# Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>\n#\n# Licensed under the GNU GPL License, Version 3.0 (the \"License\");\n"
  },
  {
    "path": "scripts/make-droplet.py",
    "chars": 2556,
    "preview": "# Copyright © 2024 Mahmoud Mousa <m.mousa@hey.com>\n#\n# Licensed under the GNU GPL License, Version 3.0 (the \"License\");\n"
  },
  {
    "path": "utils/auth.go",
    "chars": 3901,
    "preview": "package utils\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"os/exec\"\n\t\"os/user\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github."
  },
  {
    "path": "utils/config.go",
    "chars": 2464,
    "preview": "/*\nCopyright © 2024 Mahmoud Mousa <m.mousa@hey.com>\n\nLicensed under the GNU GPL License, Version 3.0 (the \"License\");\nyo"
  },
  {
    "path": "utils/docker.go",
    "chars": 578,
    "preview": "package utils\n\nimport (\n\t\"archive/tar\"\n\t\"bytes\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nfunc TarDirectoryToReader(dir string) (i"
  },
  {
    "path": "utils/scripts.go",
    "chars": 6582,
    "preview": "/*\nCopyright © 2024 Mahmoud Mousa <m.mousa@hey.com>\n\nLicensed under the GNU GPL License, Version 3.0 (the \"License\");\nyo"
  },
  {
    "path": "utils/spinner.go",
    "chars": 811,
    "preview": "/*\nCopyright © 2024 Mahmoud Mousa <m.mousa@hey.com>\n\nLicensed under the GNU GPL License, Version 3.0 (the \"License\");\nyo"
  },
  {
    "path": "utils/stages.go",
    "chars": 3023,
    "preview": "/*\nCopyright © 2024 Mahmoud Mousa <m.mousa@hey.com>\n\nLicensed under the GNU GPL License, Version 3.0 (the \"License\");\nyo"
  },
  {
    "path": "utils/types.go",
    "chars": 3885,
    "preview": "/*\nCopyright © 2024 Mahmoud Mousa <m.mousa@hey.com>\n\nLicensed under the GNU GPL License, Version 3.0 (the \"License\");\nyo"
  },
  {
    "path": "utils/utils.go",
    "chars": 7474,
    "preview": "/*\nCopyright © 2024 Mahmoud Mousa <m.mousa@hey.com>\n\nLicensed under the GNU GPL License, Version 3.0 (the \"License\");\nyo"
  },
  {
    "path": "utils/utils_test.go",
    "chars": 1899,
    "preview": "package utils_test\n\nimport (\n\t\"crypto/md5\"\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/joho/godotenv\"\n\t\"github.com/mightymoud/"
  }
]

About this extraction

This page contains the full source code of the MightyMoud/sidekick GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 30 files (183.9 KB), approximately 59.3k tokens, and a symbol index with 97 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

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

Copied to clipboard!