2023-03-10 17:52:20 +01:00
|
|
|
/*
|
|
|
|
Copyright © 2023 Laura Kalb <dev@lauka.net>
|
|
|
|
*/
|
|
|
|
|
|
|
|
package cmd
|
|
|
|
|
|
|
|
import (
|
2023-03-25 15:16:26 +01:00
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"path"
|
|
|
|
"time"
|
2023-03-10 17:52:20 +01:00
|
|
|
|
2023-03-25 15:16:26 +01:00
|
|
|
"github.com/spf13/cobra"
|
2023-03-10 17:52:20 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
var importCmd = &cobra.Command{
|
2023-03-25 15:16:26 +01:00
|
|
|
Use: "import",
|
|
|
|
Short: "Import ipam configuration (not implemented)",
|
|
|
|
Long: `Import subnets to ipam.`,
|
|
|
|
Example: "ipam import --file import.json",
|
|
|
|
Args: cobra.NoArgs,
|
|
|
|
Aliases: []string{"im"},
|
|
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
|
|
var importname string
|
|
|
|
var subnets []Subnet
|
2023-03-24 16:27:45 +01:00
|
|
|
|
2023-03-25 15:16:26 +01:00
|
|
|
flagpath, _ := cmd.Flags().GetString("file")
|
|
|
|
if path.IsAbs(flagpath) {
|
|
|
|
importname = flagpath
|
|
|
|
} else {
|
|
|
|
wd, _ := os.Getwd()
|
|
|
|
importname = path.Join(wd, flagpath)
|
|
|
|
}
|
2023-03-24 16:27:45 +01:00
|
|
|
|
2023-03-25 15:16:26 +01:00
|
|
|
file, readerr := os.ReadFile(importname)
|
|
|
|
if readerr != nil {
|
|
|
|
fmt.Printf("[ERROR] Can't read file %v\n", importname)
|
|
|
|
fmt.Println(readerr)
|
|
|
|
}
|
2023-03-24 16:27:45 +01:00
|
|
|
|
2023-03-25 15:16:26 +01:00
|
|
|
marsherr := json.Unmarshal(file, &subnets)
|
|
|
|
if marsherr != nil {
|
|
|
|
fmt.Printf("[ERROR] Invalid format for file %v\n", importname)
|
|
|
|
fmt.Println(marsherr)
|
|
|
|
}
|
2023-03-24 16:27:45 +01:00
|
|
|
|
2023-03-25 15:16:26 +01:00
|
|
|
for _, subnet := range subnets {
|
|
|
|
fmt.Printf("[INFO] Start import of %v\n", subnet.Subnet.String())
|
|
|
|
subnet.ChangedBy = "ipam import"
|
|
|
|
subnet.ChangedAt = time.Now()
|
2023-03-24 16:27:45 +01:00
|
|
|
|
2023-03-25 15:16:26 +01:00
|
|
|
for _, addr := range subnet.Addresses {
|
|
|
|
addr.ChangedBy = "ipam import"
|
|
|
|
addr.ChangedAt = time.Now()
|
|
|
|
if addr.FQDN != "" {
|
|
|
|
AddDNSFqdn(addr.FQDN, addr.IP)
|
|
|
|
}
|
|
|
|
}
|
2023-03-24 16:27:45 +01:00
|
|
|
|
2023-03-25 15:16:26 +01:00
|
|
|
suberr := subnet.WriteSubnet()
|
|
|
|
if suberr != nil {
|
|
|
|
fmt.Printf("[ERROR] Can't write subnet to file %v\n", subnet.Subnet.String())
|
|
|
|
fmt.Println(suberr)
|
|
|
|
}
|
|
|
|
fmt.Printf("[INFO] Imported subnet %v successfully\n", subnet.Subnet.String())
|
2023-03-24 16:27:45 +01:00
|
|
|
|
2023-03-25 15:16:26 +01:00
|
|
|
}
|
|
|
|
},
|
2023-03-10 17:52:20 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func init() {
|
2023-03-25 15:16:26 +01:00
|
|
|
rootCmd.AddCommand(importCmd)
|
2023-03-10 17:52:20 +01:00
|
|
|
|
2023-03-25 15:16:26 +01:00
|
|
|
importCmd.Flags().StringP("file", "f", "import.json", "File to use for import operation")
|
2023-03-10 17:52:20 +01:00
|
|
|
}
|