From 4f643269eb1bfb2c853211aebd0c1af6de93a0f0 Mon Sep 17 00:00:00 2001
From: Dennis Postma <dennis@directonline.io>
Date: Tue, 1 Oct 2024 00:30:25 +0200
Subject: [PATCH] Replace fix for tiles command

---
 src/commands/tiles.ts | 18 ++++++++++++++----
 1 file changed, 14 insertions(+), 4 deletions(-)

diff --git a/src/commands/tiles.ts b/src/commands/tiles.ts
index d7431d5..f2baf7c 100644
--- a/src/commands/tiles.ts
+++ b/src/commands/tiles.ts
@@ -3,6 +3,7 @@ import sharp from 'sharp'
 import { commandLogger } from '../utilities/logger'
 import { Server } from 'socket.io'
 import { getPublicPath } from '../utilities/utilities'
+import path from 'path'
 
 export default class TilesCommand {
   constructor(private readonly io: Server) {}
@@ -18,6 +19,7 @@ export default class TilesCommand {
     }
 
     for (const tile of tiles) {
+      console.log(getPublicPath('tiles', tile))
       // Check if tile is already 66x34
       const metadata = await sharp(getPublicPath('tiles', tile)).metadata()
       if (metadata.width === 66 && metadata.height === 34) {
@@ -26,7 +28,7 @@ export default class TilesCommand {
       }
 
       const inputPath = getPublicPath('tiles', tile)
-      const outputPath = getPublicPath('tiles', tile)
+      const tempPath = getPublicPath('tiles', `temp_${tile}`)
 
       try {
         await sharp(inputPath)
@@ -36,14 +38,22 @@ export default class TilesCommand {
             fit: 'fill',
             kernel: 'nearest'
           })
-          .toFile(outputPath)
+          .toFile(tempPath)
 
-        commandLogger.info(`Processed: ${tile}`)
+        // Replace original file with processed file
+        fs.unlinkSync(inputPath)
+        fs.renameSync(tempPath, inputPath)
+
+        commandLogger.info(`Processed and replaced: ${tile}`)
       } catch (error) {
         console.error(`Error processing ${tile}:`, error)
+        // Clean up temp file if it exists
+        if (fs.existsSync(tempPath)) {
+          fs.unlinkSync(tempPath)
+        }
       }
     }
 
     commandLogger.info('Tile processing completed.')
   }
-}
+}
\ No newline at end of file