package main

import (
	"bufio"
	"fmt"
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"

	"kisekinopureya.com.tr/updater/internal/downloader"
	"kisekinopureya.com.tr/updater/internal/logger"
	"kisekinopureya.com.tr/updater/internal/version"
)

/*
	The Steam client is known to call this program with the following parameter combinations:
	steamos-update --supports-duplicate-detection     -- should do nothing
	steamos-update --enable-duplicate-detection check -- should check for update
	steamos-update check                              -- should check for update
	steamos-update --enable-duplicate-detection       -- should perform an update
	steamos-update                                    -- should perform an update
*/

func main() {
	logger.InitializeLogger("/tmp/steamos-updatelog")

	log.Printf("%+v", os.Args)
	args := os.Args[1:]

	action := performUpdate

	switch {
	case len(args) == 1 && args[0] == "--supports-duplicate-detection":
		os.Exit(7)

	case len(args) >= 1 && args[0] == "--enable-duplicate-detection":
		if len(args) >= 2 && args[1] == "check" {
			action = checkForUpdate
		}

	case len(args) >= 1 && args[0] == "check":
		action = checkForUpdate
	}

	action()

	os.Exit(7)
}

func fetchIndex(url string) ([]string, error) {
	resp, err := http.Get(url)
	if err != nil {
		return nil, fmt.Errorf("failed to fetch index: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("bad status: %s", resp.Status)
	}

	var lines []string
	scanner := bufio.NewScanner(resp.Body)
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if line != "" {
			lines = append(lines, line)
		}
	}

	if err := scanner.Err(); err != nil {
		return nil, fmt.Errorf("reading response failed: %w", err)
	}

	return lines, nil
}

func checkForUpdate() {
	branch := version.GetCurrentBranch()
	currentVersion := version.DetermineCurrentVersion()
	currentVersionInt, err := strconv.ParseInt(currentVersion, 10, 32)
	if err != nil {
		currentVersionInt = 0 //
	}

	indexFile, err := fetchIndex("http://10.26.1.3/updates/index")
	if err != nil {
		log.Panic(err)
	}
	for _, s := range indexFile {
		if strings.HasPrefix(s, string(branch)) && !strings.HasSuffix(s, ".sig") {
			parts := strings.Split(s, "/")
			base := parts[len(parts)-1]

			// Remove extension
			base = strings.TrimSuffix(base, ".tar.xz")

			// Split by dash
			tokens := strings.Split(base, "-")
			versionFromFile := tokens[len(tokens)-1]
			versionFromFileInt, err := strconv.ParseInt(versionFromFile, 10, 32)
			if err != nil {
				log.Panic(err)
			}
			if currentVersionInt < versionFromFileInt {
				fmt.Printf("Update available: %s\n", base)
				os.Exit(0)
			}
		}
	}
}

func performUpdate() {
	branch := version.GetCurrentBranch()
	err := downloader.DownloadFile("http://10.26.1.3/updates/"+branch+"/latest.tar.xz.sig", "/var/cache/updates/update.tar.xz.sig", true)
	if err != nil {
		log.Panic(err)
	}
	err = downloader.DownloadFile("http://10.26.1.3/updates/"+branch+"/latest.tar.xz", "/var/cache/updates/update.tar.xz", false)
	if err != nil {
		log.Panic(err)
	}
	os.Exit(0)
}
