package io.gitlab.jfronny.inceptum.cli; import io.gitlab.jfronny.inceptum.Inceptum; import io.gitlab.jfronny.inceptum.model.inceptum.CommandArguments; import io.gitlab.jfronny.inceptum.model.inceptum.UpdateInfo; import io.gitlab.jfronny.inceptum.util.JvmUtils; import io.gitlab.jfronny.inceptum.util.OSCheck; import io.gitlab.jfronny.inceptum.util.UpdateChecker; import io.gitlab.jfronny.inceptum.util.Utils; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; public class UpdateCheckCommand extends Command { public UpdateCheckCommand() { super("Checks for updates, allows updating if an update is discovered via the \"install\" flag", "update"); } @Override public void invoke(CommandArguments args) { if (args.contains("install") && !args.wrapped) { System.err.println("Automatic updates are not supported without the wrapper"); return; } UpdateInfo updateUrl = getUpdate(); if (updateUrl == null) { System.out.println("No update was found"); } else { if (args.length > 1 && args.contains("install")) { System.out.println("Installing from " + updateUrl); try { update(updateUrl, false); } catch (IOException | URISyntaxException e) { e.printStackTrace(); System.err.println("Could not download update"); } } else { System.out.println("An update was found: " + updateUrl); } } } public static UpdateInfo getUpdate() { return UpdateChecker.check(Inceptum.CONFIG.channel, Inceptum.VERSION.version, Inceptum.VERSION.flavor, channel -> { Inceptum.LOGGER.error("No stable version was found, switching to experimental channel"); Inceptum.CONFIG.channel = channel; Inceptum.saveConfig(); }, Inceptum.LOGGER::info, Inceptum.LOGGER::error, Inceptum.LOGGER::error); } public static void update(UpdateInfo source, boolean relaunch) throws IOException, URISyntaxException { Inceptum.LOGGER.info("Downloading " + source.url()); Path jarPath = Inceptum.LIBRARIES_DIR.resolve("io/gitlab/jfronny/inceptum/Inceptum") .resolve(source.newVersion().toString()) .resolve("Inceptum-" + source.newVersion() + '-' + OSCheck.OS.getMojName() + ".jar") .toAbsolutePath(); Files.createDirectories(jarPath.getParent()); Utils.downloadFile(source.url(), source.sha1(), jarPath); if (relaunch) { Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { System.out.println(); new ProcessBuilder(JvmUtils.getJvm(), "-jar", jarPath.toString()) .inheritIO() .start(); } catch (IOException e) { e.printStackTrace(); } })); } } }