package main

import (
    "fmt"
    "path/filepath"
    "archive/zip"
    "github.com/arzumify/webview_go-4.1"
    "net/http"
    "os"
    "io"
    "strconv"
)

func upgrade(path string) {
    err := os.RemoveAll(filepath.Join(path, "website"))
    if err != nil {
        fmt.Println("[ERROR] Failed to delete current version:", err)
        return
    }
    err = os.MkdirAll(filepath.Join(path, "website"), os.ModePerm)
    if err != nil {
        fmt.Println("[ERROR] Failed to create website directory:", err)
	return
    }
    resp, err := http.Get("https://centrifuge.hectabit.org/HectaBit/Burgernotes-client-web/archive/main.zip")
    if err != nil {
       	fmt.Println("[ERROR] Cannot fetch latest version:", err)
        return
    }
    defer resp.Body.Close()
    tempFile, err := os.CreateTemp("", "upgrade_*.zip")
    if err != nil {
        fmt.Println("[ERROR] Failed to create temporary file:", err)
        return
    }
    defer os.Remove(tempFile.Name())
    _, err = io.Copy(tempFile, resp.Body)
    if err != nil {
        fmt.Println("[ERROR] Failed to copy zip content to temporary file:", err)
        return
    }
    zipReader, err := zip.OpenReader(tempFile.Name())
    if err != nil {
        fmt.Println("[ERROR] Failed to open zip file:", err)
        return
    }
    defer zipReader.Close()
    for _, file := range zipReader.File {
        dstPath := filepath.Join(filepath.Join(path, "website"), file.Name)
        if file.FileInfo().IsDir() {
            os.MkdirAll(dstPath, os.ModePerm)
            continue
        }
        fileReader, err := file.Open()
        if err != nil {
            fmt.Println("[ERROR] Failed to open file in zip:", err)
            return
        }
        defer fileReader.Close()
        dstFile, err := os.Create(dstPath)
        if err != nil {
            fmt.Println("[ERROR] Failed to create destination file:", err)
            return
        }
        defer dstFile.Close()
        _, err = io.Copy(dstFile, fileReader)
        if err != nil {
            fmt.Println("[ERROR] Failed to copy file contents:", err)
            return
        }
    }
    src, err := os.Open(filepath.Join(filepath.Join(path, "website"), "burgernotes-client-web"))
    if err != nil {
        fmt.Println("[ERROR] Cannot find created folder:", err)
        return
    }
    files, err := src.Readdir(-1)
    if err != nil {
        fmt.Println("[ERROR] Failed to read files:", err)
        return
    }
    for _, file := range files {
        srcPath := filepath.Join(filepath.Join(filepath.Join(path, "website"), "burgernotes-client-web"), file.Name())
        dstPath := filepath.Join(filepath.Join(path, "website"), file.Name())
        err := os.Rename(srcPath, dstPath)
        if err != nil {
            fmt.Println("[ERROR] Failed to move files:", err)
            return
        }
    }
    err = os.Remove(filepath.Join(filepath.Join(path, "website"), "burgernotes-client-web"))
    if err != nil {
        fmt.Println("[ERROR] Failed to delete source directory:", err)
        return
    }
    file, err := os.OpenFile(filepath.Join(filepath.Join(path, "website"), "index.html"), os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
    if err != nil {
        fmt.Println("[ERROR] Failed to open index.html:", err)
        return
    }
    defer file.Close()
    filecontent := "<!DOCTYPE html><html><head><title>Burgernotes</title><meta charset=\"UTF-8\" /><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /><meta http-equiv=\"refresh\" content=\"0; url=/app\"><head>Redirecting...<script>window.location.replace(\"/app\")</script>"
    _, err = file.WriteString(filecontent)
    if err != nil {
        fmt.Println("[ERROR] Failed to replace index.html:", err)
        return
    }
}

func vcheck(path string) {
    localVersion, err := os.ReadFile(path + "/website/static/version.txt")
    if err != nil {
        fmt.Println("[ERROR] Cannot get local version:", err)
        os.Exit(1)
    }
    localVersionNum, err := strconv.Atoi(string(localVersion))
    if err != nil {
        fmt.Println("[ERROR] Failed to convert local version to integer:", err)
        return
    }
    resp, err := http.Get("https://notes.hectabit.org/static/version.txt")
    if err != nil {
        fmt.Println("[ERROR] Cannot fetch remote version:", err)
        return
    }
    remoteVersion, err := io.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("[ERROR] Failed to read remote version:", err)
        return
    }
    defer resp.Body.Close()
    remoteVersionNum, err := strconv.Atoi(string(remoteVersion))
    if err != nil {
        fmt.Println("[ERROR] Failed to convert remote version to integer:", err)
        return
    }
    if localVersionNum < remoteVersionNum {
        fmt.Println("[INFO] Local version is old. Attempting upgrade...")
        upgrade(path)
    } else {
        fmt.Println("[INFO] Up to date")
    }
}

func main() {
    exepath, _ := os.Executable()
    path, _ := filepath.EvalSymlinks(exepath)
    go func() {
        http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir(filepath.Dir(path) + "/website"))))
        http.ListenAndServe("localhost:52064", nil)
    }()
    vcheck(filepath.Dir(path))

    w := webview.New(false)
    defer w.Destroy()
    w.SetTitle("Burgernotes")
    w.SetSize(800, 800, webview.HintNone)
    w.Navigate("http://localhost:52064")
    w.Run()
}
