Compare commits

...

10 Commits

Author SHA1 Message Date
58ae26b4f7 Major rewrites && Added args && Using tmp
Complete rewrite of pacman database logic && Check if db.lck exists && Create db.lck when the program backups the database and delete it afterwords
2023-02-02 14:27:42 +01:00
e07cdcfeb0 Hotfix: Changed pacman database filename && Added missing logic for compressed directory 2023-01-14 04:49:39 +01:00
eb2b1edf29 Seperated Zip steps into seperate functions && Added file comparison && Now using /tmp for file operations && Experimental color output && Added extra file and directory logic
Seperated Pacman Database into it's own function so that when the function is called two times it doesn't actually do it.
Added a way to compare two files by reading every byte and then checking if it's the same or not.
For convenience sake the /tmp directory will be used for all temporary file operations like compressing.
Color output is going great. Looks pretty nice.
Before doing anything file related all functions check if the necessary directory exists.
2023-01-14 04:03:43 +01:00
8a0c93172c Added compression && changed directory structure 2023-01-13 14:28:52 +01:00
378c907146 Removed unused code && Added extra logic to check if things exist 2023-01-12 22:38:29 +01:00
21b61759d6 Removed update functionality && Rewrote/simplified file handling && Expanded README
With this commit I will change the scope of this project. The new goal for this project is to rewrite the file handling of the original update script in C#. Because of this a lot changed with this commit.
I removed all update functionality from the code. I completely rewrote the file handling with help of the FileInfo class. I also added a couple of things to the Roadmap. While doing that I also added sources that I frequently use.
2023-01-11 04:47:58 +01:00
ed5286435a Interactive shell commands now work
The code for this was written by gpt3
2022-12-06 16:53:10 +01:00
ebf5b9e304 Copy files to backup folder in home 2022-12-06 13:23:56 +01:00
fd07d1ce74 Copy function && Separate function for everything 2022-12-06 12:23:45 +01:00
263f69b2b8 Made a seperate class for the update script 2022-12-05 18:19:18 +01:00
5 changed files with 346 additions and 24 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
.vscode/
obj/
bin/
justdoit.sh

View File

@ -1,22 +1,57 @@
using System.Diagnostics;
public class Program {
static void Main(string[] args) {
string homePath;
if(Environment.OSVersion.Platform == PlatformID.Unix) {
homePath = Environment.GetEnvironmentVariable("HOME");
} else {
Console.WriteLine("This script doesn't support your operating system.");
string beforeUpdate() {
Update.copyEverthingBeforeUpdateToBackupLocation();
Update.zipAllContentInBackupLocation("pre-backup.zip");
Update.zipPacmanDatabase();
Console.ForegroundColor = ConsoleColor.Green;
return "pre-backup complete";
}
Process process = new Process();
string postUpdate() {
ProcessStartInfo processStartInfo = new ProcessStartInfo();
//processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
processStartInfo.FileName = @"yay";
//processStartInfo.WorkingDirectory = homePath;
//processStartInfo.Arguments = "--color";
processStartInfo.RedirectStandardOutput = false;
processStartInfo.RedirectStandardError = false;
processStartInfo.UseShellExecute = true;
Update.copyEverthingAfterUpdateToBackupLocation();
Update.zipAllContentInBackupLocation("post-backup.zip");
Update.copyEverthingFromBackupLocationToFinalDestination(args[0]);
process.StartInfo = processStartInfo;
process.Start();
Console.ForegroundColor = ConsoleColor.Green;
return "post-backup complete";
}
string testPacmanDatabase() {
Update.zipPacmanDatabase();
Console.ForegroundColor = ConsoleColor.Yellow;
return "Test complete";
}
// Use https://learn.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?redirectedfrom=MSDN&view=net-7.0
try {
switch(args[1]) {
case "pre-backup":
beforeUpdate();
Console.ResetColor();
break;
case "post-backup":
postUpdate();
Console.ResetColor();
break;
case "testPacmanDatabase":
testPacmanDatabase();
Console.ResetColor();
break;
default:
Console.WriteLine("Wait! How did you do that?");
break;
}
} catch (Exception e) {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e.Message);
}
}
}

View File

@ -1,6 +1,8 @@
# update-c#
A rewrite of the legendary update script in C#
This time with file handling entirely in C# while keeping all scripting parts in bash.
## Authors
- [@ProfessionalUwU](http://192.168.0.69:3000/ProfessionalUwU)
@ -46,11 +48,20 @@ Run executable
```bash
./update
```
## Roadmap
## Roadmap/ToDo
- Figure out how to do options/arguments
- Backup important files
- Figure out how to make a single executable
- Backup all necessary files
- Hopefully shrink size of the executable
- Potentially speed up file handling
- Color output according to state (success = green, failure = red, info = yellow)
- Option to change backup location (instead of home)
- Keep backups for a configurable amount of days
## Sites I used to help make this project
- [dotnetperls](https://dotnetperls.com)
- [stackoverflow](https://stackoverflow.com/questions/tagged/c%23)
- [c-sharpcorner](https://www.c-sharpcorner.com)
## Contributing
Contributions are always welcome!

271
Update.cs Normal file
View File

@ -0,0 +1,271 @@
using System.Diagnostics;
using System.IO.Compression;
public class Update {
public static string getHomePath() {
string homePath = string.Empty;
if (Environment.OSVersion.Platform == PlatformID.Unix) {
homePath = Environment.GetEnvironmentVariable("HOME");
return homePath;
} else {
throw new ApplicationException("This script doesn't support your operating system.");
}
}
public static string copyEverthingBeforeUpdateToBackupLocation() {
string targetPath = "/tmp/backup/uncompressed/";
if (File.Exists(targetPath + "pacman-after.txt") && File.Exists(targetPath + "flatpak-after.txt")) {
File.Delete(targetPath + "pacman-after.txt");
File.Delete(targetPath + "flatpak-after.txt");
}
string[] systemFilesToCopy = {"/etc/fstab", "/etc/makepkg.conf"};
List<string> filesToCopy = new List<string>(systemFilesToCopy);
string pacmanPackageListBeforeUpdate = targetPath + "pacman-pre.txt";
filesToCopy.Add(pacmanPackageListBeforeUpdate);
string flatpakListBeforeUpdate = targetPath+ "flatpak-pre.txt";
filesToCopy.Add(flatpakListBeforeUpdate);
if (!Directory.Exists(targetPath)) {
Directory.CreateDirectory(targetPath);
copyEverthingBeforeUpdateToBackupLocation();
} else {
foreach (string file in filesToCopy) {
FileInfo info = new FileInfo(file);
string destFile = Path.Combine(targetPath, info.Name);
File.Copy(info.FullName, destFile, true);
}
}
string copiedFiles = string.Join(", ", filesToCopy);
Console.ForegroundColor = ConsoleColor.Green;
return $"Copied {copiedFiles} to {targetPath}";
}
public static string copyEverthingAfterUpdateToBackupLocation() {
string targetPath = "/tmp/backup/uncompressed/"; // Use /tmp to zip and then move into /backup/compressed/
if (File.Exists(targetPath + "pacman-pre.txt") && File.Exists(targetPath + "flatpak-pre.txt")) {
File.Delete(targetPath + "pacman-pre.txt");
File.Delete(targetPath + "flatpak-pre.txt");
File.Delete(targetPath + "fstab");
File.Delete(targetPath + "makepkg.conf");
}
List<string> filesToCopy = new List<string>();
string pacmanPackageListBeforeUpdate = targetPath + "pacman-after.txt";
filesToCopy.Add(pacmanPackageListBeforeUpdate);
string flatpakListBeforeUpdate = targetPath + "flatpak-after.txt";
filesToCopy.Add(flatpakListBeforeUpdate);
if (!Directory.Exists(targetPath)) {
Directory.CreateDirectory(targetPath);
copyEverthingAfterUpdateToBackupLocation();
} else {
foreach (string file in filesToCopy) {
FileInfo info = new FileInfo(file);
string destFile = Path.Combine(targetPath, info.Name);
File.Copy(info.FullName, destFile, true);
}
}
string copiedFiles = string.Join(", ", filesToCopy);
Console.ForegroundColor = ConsoleColor.Green;
return $"Copied {copiedFiles} to {targetPath}";
}
/// <summary>
/// Method <c>copyEverthingFromBackupLocationToFinalDestination</c> copies everything to second Backup Location which should be a external drive or a network share. Offsite/Second Backup.
/// </summary>
public static string copyEverthingFromBackupLocationToFinalDestination(string finalBackupLocation) {
string targetPath = finalBackupLocation;
if (!Directory.Exists(targetPath)) {
Console.ForegroundColor = ConsoleColor.Red;
return $"Backup location does not exist! Please specify one in the config.";
}
if (targetPath is not null) {
string sourcePath = getHomePath() + "/backup/compressed/";
string[] intermediateBackupLocation = Directory.GetFiles(sourcePath);
if (!Directory.Exists(targetPath)) {
throw new DirectoryNotFoundException("Target directory not found");
} else {
foreach (string file in intermediateBackupLocation) {
FileInfo info = new FileInfo(file);
string destFile = Path.Combine(targetPath, info.Name);
File.Copy(info.FullName, destFile, true);
}
}
Console.ForegroundColor = ConsoleColor.Green;
return $"Copied everything successfully to {targetPath}";
} else {
Console.ForegroundColor = ConsoleColor.Red;
return "You have not configured a backup location!";
}
}
public static bool zipAllContentInBackupLocation(string finalZipName) {
string targetPath = getHomePath() + "/backup/compressed/";
if (!Directory.Exists(targetPath)) {
Directory.CreateDirectory(targetPath);
}
string sourcePath = "/tmp/backup/uncompressed/";
string targetZip = getHomePath() + "/backup/compressed/" + finalZipName;
if (!Directory.Exists("/tmp/backup/")) {
Directory.CreateDirectory("/tmp/backup/");
}
string newFinalZip = "/tmp/backup/" + finalZipName;
File.Delete(newFinalZip); // Delete residual zip's in tmp
ZipFile.CreateFromDirectory(sourcePath, newFinalZip);
if (File.Exists(targetZip)) {
if (!checkForIdenticalFile(targetZip, newFinalZip)) {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"{finalZipName} is outdated");
File.Delete(targetZip);
if (File.Exists(newFinalZip)) {
File.Delete(newFinalZip);
zipAllContentInBackupLocation(finalZipName);
} else {
File.Move(newFinalZip, targetZip);
}
} else {
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"{finalZipName} is up to date");
}
} else {
ZipFile.CreateFromDirectory(sourcePath, targetZip);
}
if (File.Exists(targetZip)) {
return true;
} else {
return false;
}
}
public static bool zipPacmanDatabase() {
string pacmanDatabaseLocation = "/var/lib/pacman/local/";
string oldPacmanDatabaseZip = getHomePath() + "/backup/compressed/pacman-database.zip";
string newPacmanDatabaseZip = "/tmp/backup/compressed/pacman-database.zip";
if (!Directory.Exists("/tmp/backup/compressed/")) {
Directory.CreateDirectory("/tmp/backup/compressed/");
}
try {
if(checkForLckFile("/var/lib/pacman/") == false) { // Only creates the zip if the db.lck doesn't exist
makeDatabaseLock();
if (File.Exists(newPacmanDatabaseZip)) { // Delete residual pacman database in tmp
File.Delete(newPacmanDatabaseZip);
deleteDatabaseLock(); // Delete previous created database lock
} else {
ZipFile.CreateFromDirectory(pacmanDatabaseLocation, newPacmanDatabaseZip); // If no zip exists create one
}
if (File.Exists(oldPacmanDatabaseZip)) {
if (!checkForIdenticalFile(oldPacmanDatabaseZip, newPacmanDatabaseZip)) {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Pacman Database is outdated");
File.Delete(oldPacmanDatabaseZip);
File.Move(newPacmanDatabaseZip, oldPacmanDatabaseZip);
} else {
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Pacman Database is up to date");
File.Delete(newPacmanDatabaseZip);
}
} else {
if (!File.Exists(newPacmanDatabaseZip)) {
ZipFile.CreateFromDirectory(pacmanDatabaseLocation, newPacmanDatabaseZip); // Create the zip in tmp
}
File.Move(newPacmanDatabaseZip, oldPacmanDatabaseZip);
}
} else {
throw new ApplicationException("db.lck exists. Please try again later.");
}
} catch (Exception e) {
//deleteDatabaseLock(); // Bad practice. Only for debug purpose!
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e.Message);
}
if (File.Exists(oldPacmanDatabaseZip)) {
deleteDatabaseLock();
return true;
} else {
return false;
}
}
private static bool checkForIdenticalFile(string existingFilePath, string newFilePath) {
byte[] existingFile = File.ReadAllBytes(existingFilePath);
byte[] newFile = File.ReadAllBytes(newFilePath);
if (existingFile.Length == newFile.Length) {
for (int i=0; i < existingFile.Length; i++) {
if (existingFile[i] != newFile[i]) {
return false;
}
}
return true;
}
return false;
}
private static bool checkForLckFile(string folderToCheck) {
if (Directory.GetFiles(folderToCheck, "*.lck").Length == 1) {
return true; // lck file exists
} else {
return false; // lck file doesn't exists
}
}
private static void makeDatabaseLock() {
var psi = new ProcessStartInfo
{
FileName = "/bin/bash",
UseShellExecute = false,
RedirectStandardOutput = true,
Arguments = string.Format("-c \"cd /var/lib/pacman/ && sudo touch db.lck && sudo chmod 000 db.lck\"")
};
using (var p = Process.Start(psi))
{
if (p != null)
{
var strOutput = p.StandardOutput.ReadToEnd();
p.WaitForExit();
}
}
}
private static void deleteDatabaseLock() {
var psi = new ProcessStartInfo
{
FileName = "/bin/bash",
UseShellExecute = false,
RedirectStandardOutput = true,
Arguments = string.Format("-c \"cd /var/lib/pacman/ && sudo rm -f db.lck\"")
};
using (var p = Process.Start(psi))
{
if (p != null)
{
var strOutput = p.StandardOutput.ReadToEnd();
p.WaitForExit();
}
}
}
}

View File

@ -10,5 +10,9 @@
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Reference Include="System.IO.Compression" />
<Reference Include="System.IO.Compression.ZipFile" />
</ItemGroup>
</Project>