package clientcmd

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/deranjer/gvc/common/database"
	"github.com/deranjer/gvc/common/engine"
)

// InitializeRepo creates the repo directory and a new config file
func InitializeRepo(dbPath string, version string, rootPath string) (string, error) {
	cwd, err := os.Getwd()
	if err != nil {
		fmt.Printf("unable to get current working directory.. permissions issue? %s\n", err)
		return "", err
	}
	repoName := filepath.Base(cwd)
	fmt.Println("Initializing repo in dir: ", cwd)
	err = os.Mkdir(".gvc", 0644)
	if err != nil {
		fmt.Printf(".gvc directory already exists, but no config file... continuing\n")
	}
	err = engine.CreatePaths(rootPath)
	if err != nil {
		fmt.Printf("unable to create root dir paths.. permissions issue? %s\n", err)
		return "", err
	}
	fmt.Println("Creating DB...")
	err = database.CreateDB(dbPath, version, repoName)
	if err != nil {
		fmt.Printf("unable to create db: %s\n", err)
		err := os.Remove(dbPath)
		if err != nil {
			fmt.Printf("unable to roll back database, cannot delete db: %s err: %s", dbPath, err)
		}
		return "", err
	}
	fmt.Println("Adding new repo with name: ", repoName)
	return repoName, nil
}
