package gitlin

import (
  "bytes"
  "fmt"
  "strings"

  "github.com/spf13/cobra"

  "os"
  "os/exec"
  "runtime"
)

var updateCmd = &cobra.Command{
  Use:   "update",
  Short: "Update Gitlin.",
  Long:  `This command checks for updates and re-builds Gitlin.`,
  Run: func(cmd *cobra.Command, args []string) {
    update()
  },
}

func init() {
  rootCmd.AddCommand(updateCmd)
}

func update() {
  gitPull := exec.Command("git", "pull")
  curBranch := exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD")
  curBranchOut, _ := curBranch.CombinedOutput()
  ldFlags := "-X gitler.moe/suwako/gitlin/utils.Branch=" + strings.Replace(string(curBranchOut), "\n", "", -1)
  var out bytes.Buffer
  gitPull.Stdout = &out
  err := gitPull.Run()
  if out.String() == "Already up to date.\r" {
    fmt.Println("Gitlin is already up to date.")
    os.Exit(0)
  }
  if err != nil {
    fmt.Println("Couldn't run Git pull. Are you using Git?", err)
    os.Exit(1)
  }
  if runtime.GOOS == "windows" {
    err := exec.Command("go", "build", "-o", "gitlin.exe", ldFlags).Run()
    if err != nil {
      fmt.Println("Couldn't build Gitlin.", err)
      os.Exit(1)
    } else {
      fmt.Println("Gitlin updated successfully.")
      os.Exit(0)
    }
  } else {
    err := exec.Command("go", "build", "-ldflags", ldFlags).Run()
    if err != nil {
      fmt.Println("Couldn't build Gitlin.", err)
      os.Exit(1)
    } else {
      fmt.Println("Gitlin updated successfully.")
      os.Exit(0)
    }
  }
}
