View Javadoc
1   /*
2    *    Copyright 2011-2025 the original author or authors.
3    *
4    *    This program is free software; you can redistribute it and/or
5    *    modify it under the terms of the GNU General Public License
6    *    as published by the Free Software Foundation; either version 2
7    *    of the License, or (at your option) any later version.
8    *
9    *    You may obtain a copy of the License at
10   *
11   *       https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html
12   *
13   *    This program is distributed in the hope that it will be useful,
14   *    but WITHOUT ANY WARRANTY; without even the implied warranty of
15   *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   *    GNU General Public License for more details.
17   */
18  package com.hazendaz.maven.makeself;
19  
20  import java.io.BufferedInputStream;
21  import java.io.BufferedReader;
22  import java.io.File;
23  import java.io.IOException;
24  import java.io.InputStream;
25  import java.io.InputStreamReader;
26  import java.nio.charset.StandardCharsets;
27  import java.nio.file.Files;
28  import java.nio.file.Path;
29  import java.nio.file.StandardCopyOption;
30  import java.nio.file.attribute.PosixFilePermission;
31  import java.nio.file.attribute.PosixFilePermissions;
32  import java.util.ArrayList;
33  import java.util.Arrays;
34  import java.util.List;
35  import java.util.Map;
36  import java.util.Set;
37  
38  import javax.inject.Inject;
39  
40  import org.apache.commons.compress.archivers.ArchiveEntry;
41  import org.apache.commons.compress.archivers.ArchiveInputStream;
42  import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
43  import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
44  import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
45  import org.apache.commons.io.FilenameUtils;
46  import org.apache.maven.plugin.AbstractMojo;
47  import org.apache.maven.plugin.MojoExecutionException;
48  import org.apache.maven.plugin.MojoFailureException;
49  import org.apache.maven.plugins.annotations.LifecyclePhase;
50  import org.apache.maven.plugins.annotations.Mojo;
51  import org.apache.maven.plugins.annotations.Parameter;
52  import org.apache.maven.project.MavenProject;
53  import org.apache.maven.project.MavenProjectHelper;
54  import org.eclipse.aether.RepositorySystem;
55  import org.eclipse.aether.RepositorySystemSession;
56  import org.eclipse.aether.artifact.Artifact;
57  import org.eclipse.aether.artifact.DefaultArtifact;
58  import org.eclipse.aether.repository.RemoteRepository;
59  import org.eclipse.aether.resolution.ArtifactRequest;
60  import org.eclipse.aether.resolution.ArtifactResolutionException;
61  import org.eclipse.aether.resolution.ArtifactResult;
62  
63  /**
64   * The Class MakeselfMojo.
65   */
66  @Mojo(name = "makeself", defaultPhase = LifecyclePhase.VERIFY, requiresProject = false)
67  public class MakeselfMojo extends AbstractMojo {
68  
69      /**
70       * isWindows is detected at start of plugin to ensure windows needs.
71       */
72      private static final boolean WINDOWS = System.getProperty("os.name").startsWith("Windows");
73  
74      /**
75       * Permissions for makeself script results.
76       */
77      private static final String PERMISSIONS = "rwxr-xr--";
78  
79      /**
80       * Static ATTACH_ARTIFACT to maven lifecycle.
81       */
82      private static final boolean ATTACH_ARTIFACT = true;
83  
84      /**
85       * The path to git which is left blank unless portable git is used.
86       */
87      private String gitPath = "";
88  
89      /**
90       * archive_dir is the name of the directory that contains the files to be archived.
91       */
92      @Parameter(defaultValue = "makeself", property = "archiveDir", required = true)
93      private String archiveDir;
94  
95      /**
96       * file_name is the name of the archive to be created.
97       */
98      @Parameter(defaultValue = "makeself.sh", property = "fileName", required = true)
99      private String fileName;
100 
101     /**
102      * label is an arbitrary text string describing the package. It will be displayed while extracting the files.
103      */
104     @Parameter(defaultValue = "Makeself self-extractable archive", property = "label", required = true)
105     private String label;
106 
107     /**
108      * startup_script is the command to be executed from within the directory of extracted files. Thus, if you wish to
109      * execute a program contained in this directory, you must prefix your command with './'. For example, './program'
110      * will be fine.
111      */
112     @Parameter(defaultValue = "./makeself.sh", property = "startupScript", required = true)
113     private String startupScript;
114 
115     /**
116      * extension is for type of fileName being created. It defaults to 'sh' for backwards compatibility. Makeself
117      * defines 'run' as its default, therefore when using 'run', set extension to 'run'. This extension is used when
118      * attaching resulting artifact to maven.
119      *
120      * @since 1.5.0
121      */
122     @Parameter(defaultValue = "sh", property = "extension")
123     private String extension;
124 
125     /**
126      * classifier is for fileName being created to allow for more than one. If not defined, multiple artifacts will all
127      * be installed to same m2 location. The artifact will take on the project artifact where classfier is the physical
128      * name attribute you which to create for the fileName.
129      *
130      * @since 1.5.0
131      */
132     @Parameter(property = "classifier")
133     private String classifier;
134 
135     /**
136      * inline script allows user to skip strict verification of startup script for cases where script is defined
137      * directly such as 'echo hello' where 'echo' is a 'program' to run and 'hello' is one of many 'script arguments'.
138      * Behaviour of makeself plugin prior to 1.5.0 allowed for this undocumented feature which is further allowed and
139      * shown as an example in makeself. Verification therefore checks that both startupScript and scriptArgs exist only.
140      *
141      * @since 1.5.1
142      */
143     @Parameter(property = "inlineScript")
144     private boolean inlineScript;
145 
146     /**
147      * script_args are additional arguments for startup_script passed as an array.
148      *
149      * <pre>
150      * {@code
151      * <scriptArgs>
152      *   <scriptArg>arg1</scriptArg>
153      *   <scriptArg>arg2</scriptArg>
154      * </scriptArgs>
155      * }
156      * </pre>
157      */
158     @Parameter(property = "scriptArgs")
159     private List<String> scriptArgs;
160 
161     /**
162      * --version | -v : Print out Makeself version number and exit
163      *
164      * @since 1.6.0
165      */
166     @Parameter(property = "version")
167     private Boolean version;
168 
169     /**
170      * --help | -h : Print out this help message and exit (exit is custom to makeself maven plugin).
171      */
172     @Parameter(property = "help")
173     private Boolean help;
174 
175     /**
176      * --tar-quietly : Suppress verbose output from the tar command.
177      *
178      * @since 1.6.0
179      */
180     @Parameter(property = "tarQuietly")
181     private Boolean tarQuietly;
182 
183     /**
184      * --quiet | -q : Do not print any messages other than errors.
185      *
186      * @since 1.6.0
187      */
188     @Parameter(property = "quiet")
189     private Boolean quiet;
190 
191     /**
192      * --gzip : Use gzip for compression (the default on platforms on which gzip is commonly available, like Linux).
193      */
194     @Parameter(property = "gzip")
195     private Boolean gzip;
196 
197     /**
198      * --bzip2 : Use bzip2 instead of gzip for better compression. The bzip2 command must be available in the command
199      * path. It is recommended that the archive prefix be set to something like '.bz2.run', so that potential users know
200      * that they'll need bzip2 to extract it.
201      */
202     @Parameter(property = "bzip2")
203     private Boolean bzip2;
204 
205     /**
206      * --bzip3 : Use bzip3 instead of gzip for better compression. The bzip3 command must be available in the command
207      * path. It is recommended that the archive prefix be set to something like '.bz3.run', so that potential users know
208      * that they'll need bzip3 to extract it.
209      *
210      * @since 1.6.0
211      */
212     @Parameter(property = "bzip3")
213     private Boolean bzip3;
214 
215     /**
216      * --pbzip2 : Use pbzip2 instead of gzip for better and faster compression on machines having multiple CPUs. The
217      * pbzip2 command must be available in the command path. It is recommended that the archive prefix be set to
218      * something like '.pbz2.run', so that potential users know that they'll need bzip2 to extract it.
219      */
220     @Parameter(property = "pbzip2")
221     private Boolean pbzip2;
222 
223     /**
224      * --xz : Use xz instead of gzip for better compression. The xz command must be available in the command path. It is
225      * recommended that the archive prefix be set to something like '.xz.run' for the archive, so that potential users
226      * know that they'll need xz to extract it.
227      */
228     @Parameter(property = "xz")
229     private Boolean xz;
230 
231     /**
232      * --lzo : Use lzop instead of gzip for better compression. The lzop command must be available in the command path.
233      * It is recommended that the archive prefix be set to something like '.lzo.run' for the archive, so that potential
234      * users know that they'll need lzop to extract it.
235      */
236     @Parameter(property = "lzo")
237     private Boolean lzo;
238 
239     /**
240      * --lz4 : Use lz4 instead of gzip for better compression. The lz4 command must be available in the command path. It
241      * is recommended that the archive prefix be set to something like '.lz4.run' for the archive, so that potential
242      * users know that they'll need lz4 to extract it.
243      */
244     @Parameter(property = "lz4")
245     private Boolean lz4;
246 
247     /**
248      * --zstd : Use zstd for compression.
249      */
250     @Parameter(property = "zstd")
251     private Boolean zstd;
252 
253     /**
254      * --pigz : Use pigz for compression.
255      */
256     @Parameter(property = "pigz")
257     private Boolean pigz;
258 
259     /**
260      * --base64 : Encode the archive to ASCII in Base64 format (base64 command required).
261      */
262     @Parameter(property = "base64")
263     private Boolean base64;
264 
265     /**
266      * --gpg-encrypt : Encrypt the archive using gpg -ac -z $COMPRESS_LEVEL. This will prompt for a password to encrypt
267      * with. Assumes that potential users have gpg installed.
268      */
269     @Parameter(property = "gpgEncrypt")
270     private Boolean gpgEncrypt;
271 
272     /**
273      * --gpg-asymmetric-encrypt-sign : Instead of compressing, asymmetrically encrypt and sign the data using GPG."
274      */
275     @Parameter(property = "gpgAsymmetricEncryptSign")
276     private Boolean gpgAsymmetricEncryptSign;
277 
278     /**
279      * --ssl-encrypt : Encrypt the archive using openssl aes-256-cbc -a -salt. This will prompt for a password to
280      * encrypt with. Assumes that the potential users have the OpenSSL tools installed.
281      */
282     @Parameter(property = "sslEncrypt")
283     private Boolean sslEncrypt;
284 
285     /**
286      * --ssl-passwd pass : Use the given password to encrypt the data using OpenSSL.
287      */
288     @Parameter(property = "sslPasswd")
289     private String sslPasswd;
290 
291     /**
292      * --ssl-pass-src : Use the given src as the source of password to encrypt the data using OpenSSL. See \"PASS PHRASE
293      * ARGUMENTS\" in man openssl. If this option is not supplied, the user wil be asked to enter encryption pasword on
294      * the current terminal.
295      */
296     @Parameter(property = "sslPassSrc")
297     private String sslPassSrc;
298 
299     /**
300      * --ssl-no-md : Do not use \"-md\" option not supported by older OpenSSL.
301      */
302     @Parameter(property = "sslNoMd")
303     private Boolean sslNoMd;
304 
305     /**
306      * --compress : Use the UNIX compress command to compress the data. This should be the default on all platforms that
307      * don't have gzip available.
308      */
309     @Parameter(property = "compress")
310     private Boolean compress;
311 
312     /**
313      * --complevel : Specify the compression level for gzip, bzip2, bzip3, pbzip2, xz, lzo or lz4. (defaults to 9).
314      */
315     @Parameter(property = "complevel")
316     private Integer complevel;
317 
318     /**
319      * --nochown : Do not give the target folder to the current user (default)
320      *
321      * @since 1.6.0
322      */
323     @Parameter(property = "nochown")
324     private Boolean nochown;
325 
326     /**
327      * --chown : Give the target folder to the current user recursively
328      *
329      * @since 1.6.0
330      */
331     @Parameter(property = "chown")
332     private Boolean chown;
333 
334     /**
335      * --nocomp : Do not use any compression for the archive, which will then be an uncompressed TAR.
336      */
337     @Parameter(property = "nocomp")
338     private Boolean nocomp;
339 
340     /**
341      * --threads : Specify the number of threads to be used by compressors that support parallelization. Omit to use
342      * compressor's default. Most useful (and required) for opting into xz's threading, usually with --threads=0 for all
343      * available cores. pbzip2 and pigz are parallel by default, and setting this value allows limiting the number of
344      * threads they use.
345      */
346     @Parameter(property = "threads")
347     private Integer threads;
348 
349     /**
350      * --notemp : The generated archive will not extract the files to a temporary directory, but in a new directory
351      * created in the current directory. This is better to distribute software packages that may extract and compile by
352      * themselves (i.e. launch the compilation through the embedded script).
353      */
354     @Parameter(property = "notemp")
355     private Boolean notemp;
356 
357     /**
358      * --needroot : Check that the root user is extracting the archive before proceeding
359      *
360      * @since 1.6.0
361      */
362     @Parameter(property = "needroot")
363     private Boolean needroot;
364 
365     /**
366      * --current : Files will be extracted to the current directory, instead of in a subdirectory. This option implies
367      * --notemp and ddoes not require aq startup_script.
368      */
369     @Parameter(property = "current")
370     private Boolean current;
371 
372     /**
373      * --follow : Follow the symbolic links inside of the archive directory, i.e. store the files that are being pointed
374      * to instead of the links themselves.
375      */
376     @Parameter(property = "follow")
377     private Boolean follow;
378 
379     /**
380      * --noprogress : Do not show the progress during the decompression
381      *
382      * @since 1.6.0
383      */
384     @Parameter(property = "noprogress")
385     private Boolean noprogress;
386 
387     /**
388      * --append (new in 2.1.x): Append data to an existing archive, instead of creating a new one. In this mode, the
389      * settings from the original archive are reused (compression type, label, embedded script), and thus don't need to
390      * be specified again on the command line.
391      */
392     @Parameter(property = "append")
393     private Boolean append;
394 
395     /**
396      * --header: Makeself 2.0 uses a separate file to store the header stub, called makeself-header.sh. By default, it
397      * is assumed that it is stored in the same location as makeself.sh. This option can be used to specify its actual
398      * location if it is stored someplace else. This is not required for this plugin as the header is provided.
399      */
400     @Parameter(property = "headerFile")
401     private String headerFile;
402 
403     /**
404      * --preextract: Specify a pre-extraction script. The script is executed with the same environment and initial
405      * `script_args` as `startup_script`.
406      *
407      * @since 1.7.0
408      */
409     @Parameter(property = "preextractScript")
410     private String preextractScript;
411 
412     /**
413      * --cleanup: Specify a script that is run when execution is interrupted or finishes successfully. The script is
414      * executed with the same environment and initial `script_args` as `startup_script`.
415      */
416     @Parameter(property = "cleanupScript")
417     private String cleanupScript;
418 
419     /**
420      * --copy : Upon extraction, the archive will first extract itself to a temporary directory. The main application of
421      * this is to allow self-contained installers stored in a Makeself archive on a CD, when the installer program will
422      * later need to unmount the CD and allow a new one to be inserted. This prevents "Filesystem busy" errors for
423      * installers that span multiple CDs.
424      */
425     @Parameter(property = "copy")
426     private Boolean copy;
427 
428     /** --nox11 : Disable the automatic spawning of a new terminal in X11. */
429     @Parameter(property = "nox11")
430     private Boolean nox11;
431 
432     /** --nowait : Do not wait for user input after executing embedded program from an xterm. */
433     @Parameter(property = "nowait")
434     private Boolean nowait;
435 
436     /**
437      * --nomd5 : Disable the creation of a MD5 checksum for the archive. This speeds up the extraction process if
438      * integrity checking is not necessary.
439      */
440     @Parameter(property = "nomd5")
441     private Boolean nomd5;
442 
443     /**
444      * --nocrc : Disable the creation of a CRC checksum for the archive. This speeds up the extraction process if
445      * integrity checking is not necessary.
446      */
447     @Parameter(property = "nocrc")
448     private Boolean nocrc;
449 
450     /**
451      * --sha256 : Compute a SHA256 checksum for the archive.
452      */
453     @Parameter(property = "sha256")
454     private Boolean sha256;
455 
456     /**
457      * --sign passphrase : Signature private key to sign the package with.
458      *
459      * @since 1.6.0
460      */
461     @Parameter(property = "signPassphrase")
462     private String signPassphrase;
463 
464     /**
465      * --lsm file : Provide and LSM file to makeself, that will be embedded in the generated archive. LSM files are
466      * describing a software package in a way that is easily parseable. The LSM entry can then be later retrieved using
467      * the --lsm argument to the archive. An example of a LSM file is provided with Makeself.
468      */
469     @Parameter(property = "lsmFile")
470     private String lsmFile;
471 
472     /**
473      * --gpg-extra opt : Append more options to the gpg command line.
474      */
475     @Parameter(property = "gpgExtraOpt")
476     private String gpgExtraOpt;
477 
478     /**
479      * --tar-format opt :Specify the tar archive format (default is ustar); you may use any value accepted by your tar
480      * command (such as posix, v7, etc).
481      */
482     @Parameter(property = "tarFormatOpt")
483     private String tarFormatOpt;
484 
485     /**
486      * --tar-extra opt : Append more options to the tar command line.
487      * <p>
488      * For instance, in order to exclude the .git directory from the packaged archive directory using the GNU tar, one
489      * can use makeself.sh --tar-extra "--exclude=.git" ...
490      */
491     @Parameter(property = "tarExtraOpt")
492     private String tarExtraOpt;
493 
494     /**
495      * --untar-extra opt : Append more options to the during the extraction of the tar archive.
496      */
497     @Parameter(property = "untarExtraOpt")
498     private String untarExtraOpt;
499 
500     /**
501      * --target dir : Specify the directory where the archive will be extracted. This option implies --notemp and does
502      * not require a startup_script.
503      *
504      * @since 1.6.0
505      */
506     private String extractTargetDir;
507 
508     /**
509      * --keep-umask : Keep the umask set to shell default, rather than overriding when executing self-extracting
510      * archive.
511      */
512     @Parameter(property = "keepUmask")
513     private Boolean keepUmask;
514 
515     /**
516      * --export-conf : Export configuration variables to startup_script.
517      */
518     @Parameter(property = "exportConf")
519     private Boolean exportConf;
520 
521     /**
522      * --packaging-date date : Use provided string as the packaging date instead of the current date.
523      */
524     @Parameter(property = "packagingDate")
525     private String packagingDate;
526 
527     /**
528      * --license : Append a license file.
529      */
530     @Parameter(property = "licenseFile")
531     private String licenseFile;
532 
533     /**
534      * --nooverwrite : Do not extract the archive if the specified target directory already exists.
535      */
536     @Parameter(property = "nooverwrite")
537     private Boolean nooverwrite;
538 
539     /**
540      * --help-header file : Add a header to the archive's --help output.
541      */
542     @Parameter(property = "helpHeaderFile")
543     private String helpHeaderFile;
544 
545     /** Skip run of plugin. */
546     @Parameter(defaultValue = "false", property = "makeself.skip")
547     private boolean skip;
548 
549     /** Auto run : When set to true, resulting shell will be run. This is useful for testing purposes. */
550     @Parameter(defaultValue = "false", property = "autoRun")
551     private boolean autoRun;
552 
553     /** The build target. */
554     @Parameter(defaultValue = "${project.build.directory}/", readonly = true)
555     private String buildTarget;
556 
557     /** The makeself temp directory. */
558     @Parameter(defaultValue = "${project.build.directory}/makeself-tmp/", readonly = true)
559     private File makeselfTempDirectory;
560 
561     /** Maven ProjectHelper. */
562     @Inject
563     private MavenProjectHelper projectHelper;
564 
565     /** Maven Artifact Factory. */
566     @Inject
567     private RepositorySystem repositorySystem;
568 
569     /** Maven Project. */
570     @Parameter(defaultValue = "${project}", readonly = true, required = true)
571     private MavenProject project;
572 
573     /** Maven Repository System Session. */
574     @Parameter(defaultValue = "${repositorySystemSession}", readonly = true, required = true)
575     private RepositorySystemSession repoSession;
576 
577     /** Maven Remote Repositories. */
578     @Parameter(defaultValue = "${project.remoteProjectRepositories}", readonly = true, required = true)
579     protected List<RemoteRepository> remoteRepositories;
580 
581     /** The makeself. */
582     private Path makeself;
583 
584     /** Portable Git. */
585     private PortableGit portableGit;
586 
587     @Override
588     public void execute() throws MojoExecutionException, MojoFailureException {
589         // Check if plugin run should be skipped
590         if (this.skip) {
591             getLog().info("Makeself is skipped");
592             return;
593         }
594 
595         // Validate archive directory exists
596         Path path = Path.of(buildTarget.concat(archiveDir));
597         if (!Files.exists(path)) {
598             throw new MojoExecutionException("ArchiveDir: missing '" + buildTarget.concat(archiveDir) + "'");
599         }
600 
601         // Validate inline script or startup script file
602         if (inlineScript) {
603             // Validate inline script has script args
604             if (scriptArgs == null) {
605                 throw new MojoExecutionException("ScriptArgs required when running inlineScript");
606             }
607         } else {
608             // Validate startupScript file starts with './'
609             if (!startupScript.startsWith("./")) {
610                 throw new MojoExecutionException("StartupScript required to start with './'");
611             }
612 
613             // Validate startupScript file exists
614             path = Path.of(buildTarget.concat(archiveDir).concat(startupScript.substring(1)));
615             if (!Files.exists(path)) {
616                 throw new MojoExecutionException("StartupScript: missing '"
617                         + buildTarget.concat(archiveDir).concat(startupScript.substring(1)) + "'");
618             }
619         }
620 
621         // Setup make self files
622         this.extractMakeself();
623 
624         // Check git setup
625         if (MakeselfMojo.WINDOWS) {
626             this.checkGitSetup();
627         }
628 
629         try {
630             // Output version of bash
631             getLog().debug("Execute Bash Version");
632             execute(Arrays.asList(gitPath + "bash", "--version"), !ATTACH_ARTIFACT);
633 
634             // Output version of makeself.sh
635             getLog().debug("Execute Makeself Version");
636             execute(Arrays.asList(gitPath + "bash", makeself.toAbsolutePath().toString(), "--version"),
637                     !ATTACH_ARTIFACT);
638 
639             // If version arguments supplied, exit as we just printed version.
640             if (isTrue(version)) {
641                 return;
642             }
643 
644             // If help arguments supplied, write output and get out of code.
645             if (isTrue(help)) {
646                 getLog().debug("Execute Makeself Help");
647                 execute(Arrays.asList(gitPath + "bash", makeself.toAbsolutePath().toString(), "--help"),
648                         !ATTACH_ARTIFACT);
649                 return;
650             }
651 
652             // Basic Configuration
653             getLog().debug("Loading Makeself Basic Configuration");
654             List<String> target = new ArrayList<>(
655                     Arrays.asList(gitPath + "bash", makeself.toAbsolutePath().toString()));
656             target.addAll(loadArgs());
657             target.add(buildTarget.concat(archiveDir));
658             target.add(buildTarget.concat(fileName));
659             target.add(label);
660             target.add(startupScript);
661             if (scriptArgs != null) {
662                 target.addAll(scriptArgs);
663             }
664 
665             // Indicate makeself running
666             getLog().info("Running makeself build");
667 
668             // Execute main run of makeself.sh
669             getLog().debug("Execute Makeself Build");
670             execute(target, ATTACH_ARTIFACT);
671 
672             // Output info on file makeself created
673             getLog().debug("Execute Makeself Info on Resulting Shell Script");
674             execute(Arrays.asList(gitPath + "bash", buildTarget.concat(fileName), "--info"), !ATTACH_ARTIFACT);
675 
676             // Output list on file makeself created (non windows need)
677             if (!MakeselfMojo.WINDOWS) {
678                 getLog().debug("Execute Makeself List on Resulting Shell Script");
679                 execute(Arrays.asList(gitPath + "bash", buildTarget.concat(fileName), "--list"), !ATTACH_ARTIFACT);
680             }
681 
682             // auto run script
683             if (this.autoRun) {
684                 getLog().info("Auto-run created shell (this may take a few minutes)");
685                 execute(Arrays.asList(gitPath + "bash", buildTarget.concat(fileName)), !ATTACH_ARTIFACT);
686             }
687         } catch (IOException e) {
688             getLog().error("", e);
689         } catch (InterruptedException e) {
690             getLog().error("", e);
691             // restore interruption status of the corresponding thread
692             Thread.currentThread().interrupt();
693         }
694     }
695 
696     private void execute(List<String> target, boolean attach) throws IOException, InterruptedException {
697 
698         // Log execution target
699         getLog().debug("Execution commands: " + target);
700 
701         // Create Process Builder
702         ProcessBuilder processBuilder = new ProcessBuilder(target);
703         processBuilder.redirectErrorStream(true);
704 
705         // Add portable git to windows environment
706         if (MakeselfMojo.WINDOWS) {
707             Map<String, String> envs = processBuilder.environment();
708             getLog().debug("Environment Variables: " + envs);
709             final String location = repoSession.getLocalRepository().getBasedir() + File.separator
710                     + this.portableGit.getName() + File.separator + this.portableGit.getVersion();
711             // Windows cmd/powershell shows "Path" in this case
712             if (envs.get("Path") != null) {
713                 envs.put("Path", location + "/usr/bin;" + envs.get("Path"));
714                 getLog().debug("Environment Path Variable: " + envs.get("Path"));
715                 // Windows bash shows "PATH" in this case and has issues with spacing as in 'Program Files'
716             } else if (envs.get("PATH") != null) {
717                 envs.put("PATH",
718                         location + "/usr/bin;" + envs.get("PATH").replace("Program Files", "\"Program Files\""));
719                 getLog().debug("Environment Path Variable: " + envs.get("PATH"));
720             }
721         }
722 
723         // Create Process
724         Process process = processBuilder.start();
725 
726         // Write process output
727         try (BufferedReader reader = new BufferedReader(
728                 new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
729             String line = "";
730             while ((line = reader.readLine()) != null) {
731                 getLog().info(line);
732             }
733             getLog().info("");
734         }
735 
736         // Wait for process completion
737         int status = process.waitFor();
738         if (status > 0) {
739             getLog().error(String.join(" ", "makeself failed with error status:", String.valueOf(status)));
740         }
741 
742         // Attach artifact to maven build for install/deploy/release on success
743         if (status == 0 && attach) {
744             projectHelper.attachArtifact(project, this.extension, this.classifier,
745                     Path.of(buildTarget, FilenameUtils.getName(fileName)).toFile());
746         }
747     }
748 
749     /**
750      * Extract makeself.
751      */
752     private void extractMakeself() {
753         getLog().debug("Extracting Makeself");
754 
755         // Create makeself directory
756         Path makeselfTemp = Path.of(makeselfTempDirectory.getAbsolutePath());
757         if (!Files.exists(makeselfTemp) && !makeselfTemp.toFile().mkdirs()) {
758             getLog().error(String.join(" ", "Unable to make directory", makeselfTempDirectory.getAbsolutePath()));
759             return;
760         }
761         getLog().debug(String.join(" ", "Created directory for", makeselfTempDirectory.getAbsolutePath()));
762 
763         ClassLoader classloader = this.getClass().getClassLoader();
764 
765         // Write makeself script
766         makeself = makeselfTempDirectory.toPath().resolve("makeself.sh");
767         if (!Files.exists(makeself)) {
768             getLog().debug("Writing makeself.sh");
769             try (InputStream link = classloader.getResourceAsStream("META-INF/makeself/makeself.sh")) {
770                 Path path = makeself.toAbsolutePath();
771                 Files.copy(link, path);
772                 setFilePermissions(makeself.toFile());
773                 setPosixFilePermissions(path);
774             } catch (IOException e) {
775                 getLog().error("", e);
776             }
777         }
778 
779         // Write makeself-header script
780         Path makeselfHeader = makeselfTempDirectory.toPath().resolve("makeself-header.sh");
781         if (!Files.exists(makeselfHeader)) {
782             getLog().debug("Writing makeself-header.sh");
783             try (InputStream link = classloader.getResourceAsStream("META-INF/makeself/makeself-header.sh")) {
784                 Path path = makeselfHeader.toAbsolutePath();
785                 Files.copy(link, path);
786                 setFilePermissions(makeselfHeader.toFile());
787                 setPosixFilePermissions(path);
788             } catch (IOException e) {
789                 getLog().error("", e);
790             }
791         }
792     }
793 
794     /**
795      * Check Git Setup.
796      *
797      * @throws MojoFailureException
798      *             the mojo failure exception
799      */
800     private void checkGitSetup() throws MojoFailureException {
801         // Get Portable Git Maven Information
802         this.portableGit = new PortableGit(getLog());
803 
804         // Extract Portable Git
805         this.extractPortableGit();
806     }
807 
808     /**
809      * Extract Portable Git.
810      *
811      * @throws MojoFailureException
812      *             failure retrieving portable git
813      */
814     private void extractPortableGit() throws MojoFailureException {
815         final String location = repoSession.getLocalRepository().getBasedir() + File.separator
816                 + this.portableGit.getName() + File.separator + this.portableGit.getVersion();
817         if (Files.exists(Path.of(location))) {
818             getLog().debug("Existing 'PortableGit' folder found at " + location);
819             gitPath = location + "/usr/bin/";
820             return;
821         }
822 
823         getLog().info("Loading portable git");
824         final Artifact artifact = new DefaultArtifact(this.portableGit.getGroupId(), this.portableGit.getArtifactId(),
825                 this.portableGit.getClassifier(), this.portableGit.getExtension(), this.portableGit.getVersion());
826         final ArtifactRequest artifactRequest = new ArtifactRequest().setRepositories(this.remoteRepositories)
827                 .setArtifact(artifact);
828         ArtifactResult resolutionResult = null;
829         try {
830             resolutionResult = repositorySystem.resolveArtifact(repoSession, artifactRequest);
831             if (!resolutionResult.isResolved()) {
832                 throw new MojoFailureException("Unable to resolve artifact: " + artifact.getGroupId() + ":"
833                         + artifact.getArtifactId() + ":" + artifact.getVersion() + ":" + artifact.getClassifier() + ":"
834                         + artifact.getExtension());
835             }
836         } catch (ArtifactResolutionException e) {
837             throw new MojoFailureException(
838                     "Unable to resolve artifact: " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
839                             + artifact.getVersion() + ":" + artifact.getClassifier() + ":" + artifact.getExtension());
840         }
841         this.installGit(resolutionResult.getArtifact(), location);
842     }
843 
844     /**
845      * Install Git extracts git to .m2/repository under PortableGit.
846      *
847      * @param artifact
848      *            the maven artifact representation for git
849      * @param location
850      *            the location in maven repository to store portable git
851      */
852     private void installGit(final Artifact artifact, final String location) {
853         Path currentFile = null;
854 
855         // Unzip 'git-for-windows-*-portable.tar.gz' from '.m2/repository/com/github/hazendaz/git/git-for-windows'
856         // into '.m2/repository/PortableGit'
857         try (InputStream inputStream = Files.newInputStream(artifact.getFile().toPath());
858                 InputStream bufferedStream = new BufferedInputStream(inputStream);
859                 InputStream gzipStream = new GzipCompressorInputStream(bufferedStream);
860                 ArchiveInputStream<TarArchiveEntry> tarStream = new TarArchiveInputStream(gzipStream)) {
861             ArchiveEntry entry;
862             String directory = repoSession.getLocalRepository().getBasedir() + File.separator
863                     + this.portableGit.getName();
864             while ((entry = tarStream.getNextEntry()) != null) {
865                 if (entry.isDirectory()) {
866                     continue;
867                 }
868                 currentFile = Path.of(directory, entry.getName());
869                 if (!currentFile.normalize().startsWith(directory)) {
870                     throw new IOException("Bad zip entry, possible directory traversal");
871                 }
872                 Path parent = currentFile.getParent();
873                 if (!Files.exists(parent)) {
874                     Files.createDirectory(parent);
875                 }
876                 getLog().debug("Current file: " + currentFile.getFileName());
877                 Files.copy(tarStream, currentFile, StandardCopyOption.REPLACE_EXISTING);
878             }
879         } catch (IOException e) {
880             getLog().error("", e);
881         }
882 
883         try {
884             if (currentFile != null) {
885                 // Extract Portable Git
886                 getLog().debug("Extract Portable Git");
887                 execute(Arrays.asList(currentFile.toString(), "-y", "-o", location), !ATTACH_ARTIFACT);
888                 gitPath = location + "/usr/bin/";
889             }
890         } catch (IOException e) {
891             getLog().error("", e);
892         } catch (InterruptedException e) {
893             getLog().error("", e);
894             // restore interruption status of the corresponding thread
895             Thread.currentThread().interrupt();
896         }
897     }
898 
899     private void setFilePermissions(File file) {
900         if (!file.setExecutable(true, true)) {
901             getLog().error(String.join(" ", "Unable to set executable:", file.getName()));
902         } else {
903             getLog().debug(String.join(" ", "Set executable for", file.getName()));
904         }
905     }
906 
907     private void setPosixFilePermissions(Path path) {
908         final Set<PosixFilePermission> permissions = PosixFilePermissions.fromString(PERMISSIONS);
909 
910         try {
911             Files.setPosixFilePermissions(path, permissions);
912             getLog().debug(String.join(" ", "Set Posix File Permissions for", path.toString(), "as", PERMISSIONS));
913         } catch (IOException e) {
914             getLog().error("Failed attempted Posix permissions", e);
915         } catch (UnsupportedOperationException e) {
916             // Attempting but don't care about status if it fails
917             getLog().debug("Failed attempted Posix permissions", e);
918         }
919     }
920 
921     /**
922      * Load args.
923      *
924      * @return the string
925      */
926     private List<String> loadArgs() {
927         getLog().debug("Loading arguments");
928 
929         List<String> args = new ArrayList<>(50);
930 
931         // " --tar-quietly : Suppress verbose output from the tar command"
932         if (isTrue(tarQuietly)) {
933             args.add("--tar-quietly");
934         }
935 
936         // " --quiet | -q : Do not print any messages other than errors."
937         if (isTrue(quiet)) {
938             args.add("--quiet");
939         }
940 
941         // --gzip : Use gzip for compression (the default on platforms on which gzip is commonly available, like Linux)
942         if (isTrue(gzip)) {
943             args.add("--gzip");
944         }
945 
946         // --bzip2 : Use bzip2 instead of gzip for better compression. The bzip2 command must be available in the
947         // command path. It is recommended that the archive prefix be set to something like '.bz2.run', so that
948         // potential users know that they'll need bzip2 to extract it.
949         if (isTrue(bzip2)) {
950             args.add("--bzip2");
951         }
952 
953         // --bzip3 : Use bzip3 instead of gzip for better compression. The bzip3 command must be available in the
954         // command path. It is recommended that the archive prefix be set to something like '.bz3.run', so that
955         // potential users know that they'll need bzip3 to extract it.
956         if (isTrue(bzip3)) {
957             args.add("--bzip3");
958         }
959 
960         // --pbzip2 : Use pbzip2 instead of gzip for better and faster compression on machines having multiple CPUs.
961         // The pbzip2 command must be available in the command path. It is recommended that the archive prefix be
962         // set to something like '.pbz2.run', so that potential users know that they'll need bzip2 to extract it.
963         if (isTrue(pbzip2)) {
964             args.add("--pbzip2");
965         }
966 
967         // --xz : Use xz instead of gzip for better compression. The xz command must be available in the command path.
968         // It is recommended that the archive prefix be set to something like '.xz.run' for the archive, so that
969         // potential users know that they'll need xz to extract it.
970         if (isTrue(xz)) {
971             args.add("--xz");
972         }
973 
974         // --lzo : Use lzop instead of gzip for better compression. The lzop command must be available in the command
975         // path. It is recommended that the archive prefix be set to something like '.lzo.run' for the archive, so
976         // that potential users know that they'll need lzop to extract it.
977         if (isTrue(lzo)) {
978             args.add("--lzo");
979         }
980 
981         // --lz4 : Use lz4 instead of gzip for better compression. The lz4 command must be available in the command
982         // path. It is recommended that the archive prefix be set to something like '.lz4.run' for the archive, so
983         // that potential users know that they'll need lz4 to extract it.
984         if (isTrue(lz4)) {
985             args.add("--lz4");
986         }
987 
988         // --zstd : Use zstd for compression.
989         if (isTrue(zstd)) {
990             args.add("--zstd");
991         }
992 
993         // --pigz : Use pigz for compression.
994         if (isTrue(pigz)) {
995             args.add("--pigz");
996         }
997 
998         // --base64 : Encode the archive to ASCII in Base64 format (base64 command required).
999         if (isTrue(base64)) {
1000             args.add("--base64");
1001         }
1002 
1003         // --gpg-encrypt : Encrypt the archive using gpg -ac -z $COMPRESS_LEVEL. This will prompt for a password to
1004         // encrypt with. Assumes that potential users have gpg installed.
1005         if (isTrue(gpgEncrypt)) {
1006             args.add("--gpg-encrypt");
1007         }
1008 
1009         // --gpg-asymmetric-encrypt-sign : Instead of compressing, asymmetrically encrypt and sign the data using GPG
1010         if (isTrue(gpgAsymmetricEncryptSign)) {
1011             args.add("--gpg-asymmetric-encrypt-sign");
1012         }
1013 
1014         // --ssl-encrypt : Encrypt the archive using openssl aes-256-cbc -a -salt. This will prompt for a password to
1015         // encrypt with. Assumes that the potential users have the OpenSSL tools installed.
1016         if (isTrue(sslEncrypt)) {
1017             args.add("--ssl-encrypt");
1018         }
1019 
1020         // --ssl-passwd pass : Use the given password to encrypt the data using OpenSSL.
1021         if (sslPasswd != null) {
1022             args.add("--ssl-passwd");
1023             args.add(sslPasswd);
1024         }
1025 
1026         // --ssl-pass-src src : Use the given src as the source of password to encrypt the data using OpenSSL. See
1027         // \"PASS PHRASE ARGUMENTS\" in man openssl. If this option is not supplied, the user wil be asked to enter
1028         // encryption pasword on the current terminal.
1029         if (sslPassSrc != null) {
1030             args.add("--ssl-pass-src");
1031             args.add(sslPassSrc);
1032         }
1033 
1034         // --ssl-no-md : Do not use \"-md\" option not supported by older OpenSSL.
1035         if (isTrue(sslNoMd)) {
1036             args.add("--ssl-no-md");
1037         }
1038 
1039         // --compress : Use the UNIX compress command to compress the data. This should be the default on all platforms
1040         // that don't have gzip available.
1041         if (isTrue(compress)) {
1042             args.add("--compress");
1043         }
1044 
1045         // --complevel : Specify the compression level for gzip, bzip2, bzip3, pbzip2, xz, lzo or lz4. (defaults to 9)
1046         if (complevel != null) {
1047             args.add("--complevel");
1048             args.add(complevel.toString());
1049         }
1050 
1051         // --nochown : Do not give the target folder to the current user (default)
1052         if (isTrue(nochown)) {
1053             args.add("--nochown");
1054         }
1055 
1056         // --chown : Give the target folder to the current user recursively.
1057         if (isTrue(chown)) {
1058             args.add("--chown");
1059         }
1060 
1061         // --nocomp : Do not use any compression for the archive, which will then be an uncompressed TAR.
1062         if (isTrue(nocomp)) {
1063             args.add("--nocomp");
1064         }
1065 
1066         // --threads thds : Number of threads to be used by compressors that support parallelization.
1067         // Omit to use compressor's default. Most useful (and required) for opting into xz's threading,
1068         // usually with '--threads=0' for all available cores.pbzip2 and pigz are parallel by default,
1069         // and setting this value allows limiting the number of threads they use.
1070         if (threads != null) {
1071             args.add("--threads");
1072             args.add(threads.toString());
1073         }
1074 
1075         // --notemp : The generated archive will not extract the files to a temporary directory, but in a new directory
1076         // created in the current directory. This is better to distribute software packages that may extract and compile
1077         // by themselves (i.e. launch the compilation through the embedded script).
1078         if (isTrue(notemp)) {
1079             args.add("--notemp");
1080         }
1081 
1082         // --needroot : Check that the root user is extracting the archive before proceeding
1083         if (isTrue(needroot)) {
1084             args.add("--needroot");
1085         }
1086 
1087         // --current : Files will be extracted to the current directory, instead of in a sub-directory. This option
1088         // implies --notemp and does not require a startup_script.
1089         if (isTrue(current)) {
1090             args.add("--current");
1091         }
1092 
1093         // --follow : Follow the symbolic links inside of the archive directory, i.e. store the files that are being
1094         // pointed to instead of the links themselves.
1095         if (isTrue(follow)) {
1096             args.add("--follow");
1097         }
1098 
1099         // --noprogress : Do not show the progress during the decompression
1100         if (isTrue(noprogress)) {
1101             args.add("--noprogress");
1102         }
1103 
1104         // --append (new in 2.1.x): Append data to an existing archive, instead of creating a new one. In this mode, the
1105         // settings from the original archive are reused (compression type, label, embedded script), and thus don't need
1106         // to be specified again on the command line.
1107         if (isTrue(append)) {
1108             args.add("--append");
1109         }
1110 
1111         // --header : Makeself 2.0 uses a separate file to store the header stub, called makeself-header.sh. By default,
1112         // it is assumed that it is stored in the same location as makeself.sh. This option can be used to specify its
1113         // actual location if it is stored someplace else.
1114         if (headerFile != null) {
1115             args.add("--header");
1116             args.add(headerFile);
1117         }
1118 
1119         // --preextract : Specify a pre-extraction script. The script is executed with the same environment and initial
1120         // `script_args` as `startup_script`.
1121         if (preextractScript != null) {
1122             args.add("--reextract");
1123             args.add(preextractScript);
1124         }
1125 
1126         // --cleanup : Specify a script that is run when execution is interrupted or finishes successfully. The script
1127         // is executed with the same environment and initial `script_args` as `startup_script`.
1128         if (cleanupScript != null) {
1129             args.add("--cleanup");
1130             args.add(cleanupScript);
1131         }
1132 
1133         // --copy : Upon extraction, the archive will first extract itself to a temporary directory. The main
1134         // application of this is to allow self-contained installers stored in a Makeself archive on a CD, when the
1135         // installer program will later need to unmount the CD and allow a new one to be inserted. This prevents
1136         // "File system busy" errors for installers that span multiple CDs.
1137         if (isTrue(copy)) {
1138             args.add("--copy");
1139         }
1140 
1141         // --nox11 : Disable the automatic spawning of a new terminal in X11.
1142         if (isTrue(nox11)) {
1143             args.add("--nox11");
1144         }
1145 
1146         // --nowait : When executed from a new X11 terminal, disable the user prompt at the end of the script execution.
1147         if (isTrue(nowait)) {
1148             args.add("--nowait");
1149         }
1150 
1151         // --nomd5 : Disable the creation of a MD5 checksum for the archive. This speeds up the extraction process if
1152         // integrity checking is not necessary.
1153         if (isTrue(nomd5)) {
1154             args.add("--nomd5");
1155         }
1156 
1157         // --nocrc : Disable the creation of a CRC checksum for the archive. This speeds up the extraction process if
1158         // integrity checking is not necessary.
1159         if (isTrue(nocrc)) {
1160             args.add("--nocrc");
1161         }
1162 
1163         // --sha256 : Compute a SHA256 checksum for the archive.
1164         if (isTrue(sha256)) {
1165             args.add("--sha256");
1166         }
1167 
1168         // --lsm file : Provide and LSM file to makeself, that will be embedded in the generated archive. LSM files are
1169         // describing a software package in a way that is easily parseable. The LSM entry can then be later retrieved
1170         // using the --lsm argument to the archive. An example of a LSM file is provided
1171         // with Makeself.
1172         if (lsmFile != null) {
1173             args.add("--lsm");
1174             args.add(lsmFile);
1175         }
1176 
1177         // --gpg-extra opt : Append more options to the gpg command line.
1178         if (gpgExtraOpt != null) {
1179             args.add("--gpg-extra");
1180             args.add(gpgExtraOpt);
1181         }
1182 
1183         // --tar-format opt : Specify the tar archive format (default is ustar); you may use any value accepted by your
1184         // tar command (such as posix, v7, etc).
1185         if (tarFormatOpt != null) {
1186             args.add("--tar-format");
1187             args.add(tarFormatOpt);
1188         }
1189 
1190         // --tar-extra opt : Append more options to the tar command line.
1191         // For instance, in order to exclude the .git directory from the packaged archive directory using the GNU tar,
1192         // one can use makeself.sh --tar-extra "--exclude=.git" ...
1193         if (tarExtraOpt != null) {
1194             args.add("--tar-extra");
1195             args.add(tarExtraOpt);
1196         }
1197 
1198         // --untar-extra opt : Append more options to the during the extraction of the tar archive.
1199         if (untarExtraOpt != null) {
1200             args.add("--untar-extra");
1201             args.add(untarExtraOpt);
1202         }
1203 
1204         // --sign passphrase : Signature private key to sign the package with
1205         if (signPassphrase != null) {
1206             args.add("--sign");
1207             args.add(signPassphrase);
1208         }
1209 
1210         // --target dir : Specify the directory where the archive will be extracted. This option implies
1211         // --notemp and does not require a startup_script.
1212         if (extractTargetDir != null) {
1213             args.add("--target");
1214             args.add(extractTargetDir);
1215         }
1216 
1217         // --keep-umask : Keep the umask set to shell default, rather than overriding when executing self-extracting
1218         // archive.
1219         if (isTrue(keepUmask)) {
1220             args.add("--keep-umask");
1221         }
1222 
1223         // --export-conf : Export configuration variables to startup_script"
1224         if (isTrue(exportConf)) {
1225             args.add("--export-conf");
1226         }
1227 
1228         // --packaging-date date : Use provided string as the packaging date instead of the current date.
1229         if (packagingDate != null) {
1230             args.add("--packaging-date");
1231             args.add(packagingDate);
1232         }
1233 
1234         // --license : Append a license file.
1235         if (licenseFile != null) {
1236             args.add("--license");
1237             args.add(licenseFile);
1238         }
1239 
1240         // --nooverwrite : Do not extract the archive if the specified target directory already exists.
1241         if (isTrue(nooverwrite)) {
1242             args.add("--nooverwrite");
1243         }
1244 
1245         // --help-header file : Add a header to the archive's --help output.
1246         if (helpHeaderFile != null) {
1247             args.add("--help-header");
1248             args.add(helpHeaderFile);
1249         }
1250 
1251         return args;
1252     }
1253 
1254     private boolean isTrue(Boolean value) {
1255         if (value != null) {
1256             return value.booleanValue();
1257         }
1258         return false;
1259     }
1260 
1261 }