package main

import (
	"fmt"
	"log"
	"os"

	"gitea.urkob.com/urko/backblaze-backup/internal/services"
	"gitea.urkob.com/urko/backblaze-backup/kit/config"
	"github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
	Use:   "backblaze-backup",
	Short: "Backblaze backup tool",
	Long:  `A tool to backup files and directories to Backblaze.`,
	Run: func(cmd *cobra.Command, args []string) {
		log.SetFlags(log.Lmicroseconds)
		filePath, err := cmd.Flags().GetString("file")
		if err != nil {
			log.Fatalln("file %w", err)
		}
		dir, err := cmd.Flags().GetString("dir")
		if err != nil {
			log.Fatalln("dir %w", err)
		}
		bucketName, err := cmd.Flags().GetString("bucket")
		if err != nil {
			log.Fatalln("bucket %w", err)
		}

		envFile := ""
		if os.Getenv("BACKBLAZE_ENV") == "dev" {
			envFile = ".env"
		}
		cfg := config.NewConfig(envFile)

		bbService := services.NewBackBlaze(cfg.BbId, cfg.BbKey).WithBucket(bucketName).WithDir(dir).WithFile(filePath)
		if err := bbService.Sync(); err != nil {
			log.Fatalln("bbService.Sync()", err)
		}
	},
}

func init() {
	rootCmd.PersistentFlags().String("file", "", "absolute path of the file you want to upload to backblaze")
	rootCmd.PersistentFlags().String("dir", "", "absolute path of the directory you want to upload to backblaze")
	rootCmd.PersistentFlags().String("bucket", "", "backblaze bucket name")
}

func main() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}