package main

import (
	"archive/tar"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"

	"github.com/therootcompany/xz"
)

func downloadHeadless(c UsrConfig) {
	if hasInternet() == true {
		headlessQuery := "https://www.factorio.com/get-download/latest/headless/linux64"

		url := headlessQuery
		resp, err := http.Get(url)
		if err != nil || resp.StatusCode != http.StatusOK {
			log.Fatal("Download failed")
		}
		defer resp.Body.Close()

		// Wrap stream in XZ and Tar readers
		xzReader, _ := xz.NewReader(resp.Body, 0)
		tr := tar.NewReader(xzReader)

		for {
			header, err := tr.Next()
			if err == io.EOF {
				break
			}

			target := filepath.Join(".", header.Name)
			switch header.Typeflag {
			case tar.TypeDir:
				os.MkdirAll(target, 0755)
			case tar.TypeReg:
				os.MkdirAll(filepath.Dir(target), 0755)
				outFile, _ := os.Create(target)
				io.Copy(outFile, tr)
				outFile.Close()
			}
		}
		// zip does not preserve permissions correctly so i have to do this
		exec.Command("chmod", "+x", c.Server.ServExec)
	} else {
		fmt.Println("Unable to access internet, please check connection.")
	}
}
