From d4954821575ddf3f8dfc05ddbd54e2a98e6d393f Mon Sep 17 00:00:00 2001
From: RandomChars <random@chars.jp>
Date: Wed, 13 Oct 2021 11:25:46 +0900
Subject: [PATCH] implement proper parent unsetting, reject setting parent when
 already grouped

---
 store/image.go | 24 +++++++++++++++++++++---
 1 file changed, 21 insertions(+), 3 deletions(-)

diff --git a/store/image.go b/store/image.go
index 8daae1c..9df4293 100644
--- a/store/image.go
+++ b/store/image.go
@@ -315,22 +315,40 @@ func (s *Store) ImageUpdate(hash, source, parent, commentary, commentaryTranslat
 		info.Source = source
 		msg += "source"
 	}
-	if parent != "\000" && parent != "" && parent != info.Snowflake {
+
+	if parent != "\000" && parent != info.Snowflake {
 		if p := s.ImageSnowflake(parent); p.Snowflake == parent {
-			s.getLock(p.Hash).Lock()
-			defer s.getLock(p.Hash).Unlock()
+			// If no parent, then get the current parent and unset
+			if parent == "" {
+				p = s.ImageSnowflake(info.Parent)
+				// If no current parent, nothing to do
+				if p.Snowflake == "" {
+					goto end
+				}
+			} else {
+				// If setting parent but parent has child, reject
+				if p.Child != "" {
+					goto end
+				}
+			}
 
 			info.Parent = parent
 
 			// Update the parent to reflect the child
 			p.Child = info.Snowflake
+			if parent == "" {
+				p.Child = ""
+			}
+			s.getLock(p.Hash).Lock()
 			s.imageMetadataWrite(p)
+			s.getLock(p.Hash).Unlock()
 
 			if msg != "" {
 				msg += ", "
 			}
 			msg += "parent " + parent
 		}
+	end:
 	}
 	if commentary != "\000" {
 		info.Commentary = commentary
-- 
GitLab