package main

import (
	"os"
	"path/filepath"
	"strings"
)

func hookContext(hook *Hook, scannerTxt string) {
	if scannerTxt == "" {
		hook.Context = "PostCommit"
	} else if strings.HasPrefix(scannerTxt, "sandpoints-ext") {
		revs := strings.Fields(scannerTxt)
		if revs[1] == "publish" {
			hook.Publish = true
		}
		if revs[2] == "offline" {
			hook.Offline = true
		}
		if revs[3] == "file" {
			hook.Context = "SandpointsFileProtocol"
		}
		if revs[3] == "http" {
			hook.Context = "SandpointsHTTPProtocol"
		}
	} else {
		// it only handles gitea use case if not Local or sandpoints-ext
		hook.Context = "PostReceive"
		hook.Stdinput = scannerTxt
	}
}

func cleanUpPublicHTML(hugo *Hugo, hook *Hook) {
	if hook.Publish {
		if _, err := os.Stat(filepath.Join(hook.PublicHTMLPath, hugo.PublicHTMLName)); err == nil {
			err := os.RemoveAll(filepath.Join(hook.PublicHTMLPath, hugo.PublicHTMLName))
			check(err)
			err = os.MkdirAll(hook.PublicHTMLPath, 0755)
			check(err)
		}
	} else if _, err := os.Lstat(filepath.Join(hook.PublicHTMLPath, hugo.PublicHTMLName, "_preview")); err == nil {
		err := os.RemoveAll(filepath.Join(hook.PublicHTMLPath, hugo.PublicHTMLName, "_preview"))
		check(err)
	} else if _, err := os.Stat(filepath.Join(hook.PublicHTMLPath, hugo.PublicHTMLName, "_preview")); err == nil {
		err := os.RemoveAll(filepath.Join(hook.PublicHTMLPath, hugo.PublicHTMLName, "_preview"))
		check(err)
	}
}

func copyToPublicHTML(hugo *Hugo, hook *Hook) {
	if hook.Publish {
		err := os.Rename(hugo.DestinationDir, filepath.Join(hook.PublicHTMLPath, hugo.PublicHTMLName))
		check(err)
		err = os.Symlink(filepath.Join(hook.PublicHTMLPath, hugo.PublicHTMLName), filepath.Join(hook.PublicHTMLPath, hugo.PublicHTMLName, "_preview"))
		check(err)
		if hugo.CatalogPrefix != "" && hugo.CatalogName != "" {
			err = os.Symlink(filepath.Join(hook.PublicHTMLPath, "libraries", hugo.CatalogName), filepath.Join(hook.PublicHTMLPath, hugo.PublicHTMLName, hugo.CatalogPrefix))
			check(err)
		}
	} else {
		err := os.MkdirAll(filepath.Join(hook.PublicHTMLPath, hugo.PublicHTMLName), 0755)
		check(err)
		err = os.Rename(hugo.DestinationDir, filepath.Join(hook.PublicHTMLPath, hugo.PublicHTMLName, "_preview"))
		check(err)
		if hugo.CatalogPrefix != "" && hugo.CatalogName != "" {
			err = os.Symlink(filepath.Join(hook.PublicHTMLPath, "libraries", hugo.CatalogName), filepath.Join(hook.PublicHTMLPath, hugo.PublicHTMLName, "_preview", hugo.CatalogPrefix))
			check(err)
		}
	}
}
