package main import ( "database/sql" "log" "os" "git.wntrmute.dev/kyle/mcias/database" _ "github.com/mattn/go-sqlite3" "github.com/spf13/cobra" "github.com/spf13/viper" ) var ( schemaFile string ) var initCmd = &cobra.Command{ Use: "init", Short: "Initialize the MCIAS database", Long: `Initialize the MCIAS database with the default schema or a custom schema file. This command will create a new database file if it doesn't exist, or initialize an existing database.`, Run: func(cmd *cobra.Command, args []string) { initializeDatabase() }, } func init() { rootCmd.AddCommand(initCmd) initCmd.Flags().StringVarP(&schemaFile, "schema", "s", "", "Path to a custom schema file (default: embedded schema)") } func initializeDatabase() { dbPath := viper.GetString("db") logger := log.New(os.Stdout, "MCIAS: ", log.LstdFlags) db, err := sql.Open("sqlite3", dbPath) if err != nil { logger.Fatalf("Failed to open database: %v", err) } defer db.Close() var schemaSQL string if schemaFile != "" { // Use custom schema file if provided schemaBytes, err := os.ReadFile(schemaFile) if err != nil { logger.Fatalf("Failed to read custom schema file: %v", err) } schemaSQL = string(schemaBytes) } else { // Use embedded default schema var err error schemaSQL, err = database.DefaultSchema() if err != nil { logger.Fatalf("Failed to load default schema: %v", err) } } _, err = db.Exec(schemaSQL) if err != nil { logger.Fatalf("Failed to initialize database: %v", err) } logger.Println("Database initialized successfully") }