public async Task <IActionResult> StartSystemdService(int serverId)
        {
            if (!await RightsHandler.HasRightsToThisPavlovServer(HttpContext.User,
                                                                 await _userservice.getUserFromCp(HttpContext.User), serverId, _service, _pavlovServerService))
            {
                return(Forbid());
            }
            var server = await _pavlovServerService.FindOne(serverId);

            try
            {
                await RconStatic.SystemDStart(server, _pavlovServerService);
            }
            catch (CommandException e)
            {
                return(BadRequest(e.Message));
            }

            return(RedirectToAction("Index", "SshServer"));
        }
        public async Task <ConnectionResult> StartMatchWithAuth(RconService.AuthType authType,
                                                                PavlovServer server,
                                                                Match match)
        {
            var connectionInfo = RconStatic.ConnectionInfoInternal(server.SshServer, authType, out var result);

            using var clientSsh  = new SshClient(connectionInfo);
            using var clientSftp = new SftpClient(connectionInfo);
            try
            {
                var listOfSteamIdentietiesWhichCanPlay = match.MatchTeam0SelectedSteamIdentities;
                listOfSteamIdentietiesWhichCanPlay.AddRange(match.MatchTeam1SelectedSteamIdentities);
                var list = new List <string>();
                if (listOfSteamIdentietiesWhichCanPlay.Count <= 0 && match.MatchSelectedSteamIdentities.Count <= 0)
                {
                    DataBaseLogger.LogToDatabaseAndResultPlusNotify("There are no team members so no match will start!",
                                                                    LogEventLevel.Fatal, _notifyService, result);
                    return(result);
                }


                if (match.MatchSelectedSteamIdentities.Count > 0)
                {
                    list = match.MatchSelectedSteamIdentities
                           .Select(x => Strings.Trim(x.SteamIdentityId)).ToList();
                }
                else if (listOfSteamIdentietiesWhichCanPlay.Count > 0)
                {
                    list = listOfSteamIdentietiesWhichCanPlay.Select(x => Strings.Trim(x.SteamIdentityId)).ToList();
                }

                list = list.Distinct().ToList();
                //GetAllAdminsForTheMatch
                var mods = new List <string>();
                //Todo what if the match is not team based? there are no mods or admins?
                mods = listOfSteamIdentietiesWhichCanPlay.Where(x => x.OverWriteRole == "Mod" || x.OverWriteRole == "Admin").Select(x => x.SteamIdentityId).ToList();


                //Write whitelist and set server settings


                RconStatic.WriteFile(server.SshServer,
                                     server.ServerFolderPath + FilePaths.WhiteList,
                                     list.ToArray(), _notifyService);
                RconStatic.WriteFile(server.SshServer,
                                     server.ServerFolderPath + FilePaths.ModList,
                                     mods.ToArray(), _notifyService);
                RconStatic.WriteFile(server.SshServer,
                                     server.ServerFolderPath + FilePaths.BanList,
                                     Array.Empty <string>(), _notifyService);


                var oldSettings = new PavlovServerGameIni();
                oldSettings.ReadFromFile(server, _notifyService);

                var serverSettings = new PavlovServerGameIni
                {
                    bEnabled        = true,
                    ServerName      = match.Name,
                    MaxPlayers      = match.PlayerSlots,
                    bSecured        = true,
                    bCustomServer   = true,
                    bWhitelist      = true,
                    RefreshListTime = 120,
                    LimitedAmmoType = 0,
                    TickRate        = 90,
                    TimeLimit       = match.TimeLimit,
                    Password        = "",
                    BalanceTableURL = "",
                    bVerboseLogging = true,
                    bCompetitive    = true,
                    MapRotation     = new List <PavlovServerGameIniMap>
                    {
                        new()
                        {
                            MapLabel = match.MapId,
                            GameMode = match.GameMode
                        }
                    },
                    ApiKey = oldSettings.ApiKey
                };
                var map = await _mapsService.FindOne(match.MapId.Replace("UGC", ""));

                serverSettings.SaveToFile(server, new[]
                {
                    new ServerSelectedMap()
                    {
                        Map      = map,
                        GameMode = match.GameMode
                    }
                }, _notifyService);
                await RconStatic.SystemDStart(server, _pavlovServerService);

                //StartWatchServiceForThisMatch
                match.Status = Status.StartetWaitingForPlayer;
                await Upsert(match);

                DataBaseLogger.LogToDatabaseAndResultPlusNotify("Start backgroundjob", LogEventLevel.Verbose,
                                                                _notifyService);

                BackgroundJob.Enqueue(
                    () => MatchInspector(match.Id)); // ChecjServerState
            }
        public virtual async Task <PavlovServer> ValidatePavlovServer(PavlovServer pavlovServer, bool root)
        {
            DataBaseLogger.LogToDatabaseAndResultPlusNotify("start validate", LogEventLevel.Verbose, _notifyService);
            var hasToStop = false;

            await IsValidOnly(pavlovServer);


            DataBaseLogger.LogToDatabaseAndResultPlusNotify("try to start service", LogEventLevel.Verbose,
                                                            _notifyService);
            //try if the service realy exist
            try
            {
                pavlovServer = await GetServerServiceState(pavlovServer);

                if (pavlovServer.ServerServiceState != ServerServiceState.active)
                {
                    DataBaseLogger.LogToDatabaseAndResultPlusNotify("has to start", LogEventLevel.Verbose,
                                                                    _notifyService);
                    hasToStop = true;
                    //the problem is here for the validating part if it has to start the service first it has problems
                    await RconStatic.SystemDStart(pavlovServer, this);

                    pavlovServer = await GetServerServiceState(pavlovServer);

                    DataBaseLogger.LogToDatabaseAndResultPlusNotify("state = " + pavlovServer.ServerServiceState,
                                                                    LogEventLevel.Verbose, _notifyService);
                }
            }
            catch (CommandException e)
            {
                throw new ValidateException(e.Message);
            }

            DataBaseLogger.LogToDatabaseAndResultPlusNotify("try to send serverinfo", LogEventLevel.Verbose,
                                                            _notifyService);
            //try to send Command ServerInfo
            try
            {
                await RconStatic.SendCommandSShTunnel(pavlovServer, "ServerInfo", _notifyService);
            }
            catch (CommandException e)
            {
                await HasToStop(pavlovServer, hasToStop, root);

                throw new ValidateException(e.Message);
            }

            //try if the user have rights to delete maps cache
            try
            {
                DataBaseLogger.LogToDatabaseAndResultPlusNotify("delete unused maps", LogEventLevel.Verbose,
                                                                _notifyService);
                RconStatic.DeleteUnusedMaps(pavlovServer,
                                            (await _serverSelectedMapService.FindAllFrom(pavlovServer)).ToList());
            }
            catch (CommandException e)
            {
                await HasToStop(pavlovServer, hasToStop, root);

                throw new ValidateException(e.Message);
            }

            if (!string.IsNullOrEmpty(pavlovServer.SshServer.ShackMapsPath))
            {
                try
                {
                    DataBaseLogger.LogToDatabaseAndResultPlusNotify("check if ShackMapsPath exist!", LogEventLevel.Verbose,
                                                                    _notifyService);
                    RconStatic.DoesPathExist(pavlovServer, pavlovServer.SshServer.ShackMapsPath, _notifyService);
                }
                catch (CommandException e)
                {
                    await HasToStop(pavlovServer, hasToStop, root);

                    throw new ValidateException("ShackMapsPath does not exist: " + pavlovServer.SshServer.ShackMapsPath + "additional info:" + e.Message);
                }
            }

            await HasToStop(pavlovServer, hasToStop, root);

            return(pavlovServer);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="server"></param>
        /// <param name="reservedFor"></param>
        /// <exception cref="CommandExceptionCreateServerDuplicate"></exception>

        public async Task CreatePavlovServer(PavlovServerViewModel server, string reservedFor = "")
        {
            DataBaseLogger.LogToDatabaseAndResultPlusNotify("Start creting server", LogEventLevel.Verbose,
                                                            _notifyService);
            //Check stuff
            var exist = RconStatic.DoesPathExist(server, server.ServerFolderPath, _notifyService);

            if (exist)
            {
                throw new CommandExceptionCreateServerDuplicate("ServerFolderPath already exist!");
            }

            exist = RconStatic.DoesPathExist(server,
                                             "/etc/systemd/system/" + server.ServerSystemdServiceName + ".service", _notifyService);
            if (exist)
            {
                throw new CommandExceptionCreateServerDuplicate("Systemd Service already exist!");
            }

            var portsUsed = (await FindAll()).Where(x => x.SshServer.Id == server.SshServer.Id)
                            .FirstOrDefault(x => x.ServerPort == server.ServerPort || x.TelnetPort == server.TelnetPort);

            if (portsUsed != null)
            {
                if (portsUsed.ServerPort == server.ServerPort)
                {
                    throw new CommandExceptionCreateServerDuplicate("The server port is already used!");
                }

                if (portsUsed.TelnetPort == server.TelnetPort)
                {
                    throw new CommandExceptionCreateServerDuplicate("The telnet port is already used!");
                }
            }


            DataBaseLogger.LogToDatabaseAndResultPlusNotify("Start Install pavlovserver", LogEventLevel.Verbose,
                                                            _notifyService);

            DataBaseLogger.LogToDatabaseAndResultPlusNotify(
                "Username used befor changed to root: " + server.SshServer.SshUsername, LogEventLevel.Verbose,
                _notifyService);

            await RconStatic.UpdateInstallPavlovServer(server, this);


            DataBaseLogger.LogToDatabaseAndResultPlusNotify("Start Install pavlovserver service",
                                                            LogEventLevel.Verbose, _notifyService);

            var oldSSHcrid = new SshServer
            {
                SshPassphrase  = server.SshServer.SshPassphrase,
                SshUsername    = server.SshServer.SshUsername,
                SshPassword    = server.SshServer.SshPassword,
                SshKeyFileName = server.SshServer.SshKeyFileName
            };

            server.SshServer.SshPassphrase      = server.SshPassphraseRoot;
            server.SshServer.SshUsername        = server.SshUsernameRoot;
            server.SshServer.SshPassword        = server.SshPasswordRoot;
            server.SshServer.SshKeyFileName     = server.SshKeyFileNameRoot;
            server.SshServer.NotRootSshUsername = oldSSHcrid.SshUsername;

            try
            {
                await RconStatic.InstallPavlovServerService(server, _notifyService);
            }
            catch (CommandException e)
            {
                //If crash inside here the user login is still root. If the root login is bad this will fail to remove the server afterwards
                OverwrideTheNormalSSHLoginData(server, oldSSHcrid);
                DataBaseLogger.LogToDatabaseAndResultPlusNotify(
                    "Could not install service while creating the pavlov server -> " + e.Message, LogEventLevel.Verbose, _notifyService);
                throw;
            }
            OverwrideTheNormalSSHLoginData(server, oldSSHcrid);
            DataBaseLogger.LogToDatabaseAndResultPlusNotify(
                "Username used after override old infos: " + server.SshServer.SshUsername, LogEventLevel.Verbose,
                _notifyService);
            //start server and stop server to get Saved folder etc.

            DataBaseLogger.LogToDatabaseAndResultPlusNotify("Start after install", LogEventLevel.Verbose,
                                                            _notifyService);

            await RconStatic.SystemDStart(server, this);

            DataBaseLogger.LogToDatabaseAndResultPlusNotify("stop after install", LogEventLevel.Verbose,
                                                            _notifyService);

            await RconStatic.SystemDStop(server, this);

            DataBaseLogger.LogToDatabaseAndResultPlusNotify("Try to save game ini", LogEventLevel.Verbose,
                                                            _notifyService);



            var pavlovServerGameIni = new PavlovServerGameIni();

            DataBaseLogger.LogToDatabaseAndResultPlusNotify("created Ini", LogEventLevel.Verbose, _notifyService);
            var selectedMaps = await _serverSelectedMapService.FindAllFrom(server);

            DataBaseLogger.LogToDatabaseAndResultPlusNotify("found maps", LogEventLevel.Verbose, _notifyService);
            pavlovServerGameIni.ServerName = server.Name;


            pavlovServerGameIni.SaveToFile(server, selectedMaps, _notifyService);

            //also create rcon settings


            DataBaseLogger.LogToDatabaseAndResultPlusNotify("write rcon file", LogEventLevel.Verbose,
                                                            _notifyService);

            var lines = new List <string>
            {
                "Password="******"Port=" + server.TelnetPort
            };

            RconStatic.WriteFile(server.SshServer, server.ServerFolderPath + FilePaths.RconSettings,
                                 lines.ToArray(), _notifyService);
        }