bottin-agenda/cmd/scan.go

132 lines
2.8 KiB
Go
Raw Permalink Normal View History

package cmd
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
"git.agecem.com/agecem/bottin-agenda/data"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var (
protocol, host, username, password string
port int
check bool
)
// scanCmd represents the scan command
var scanCmd = &cobra.Command{
Use: "scan",
Short: "Check a bottin instance for existing membre",
Run: func(cmd *cobra.Command, args []string) {
args_length := len(args)
if args_length != 1 {
log.Fatalf("[e] Wrong number of arguments, got '%d' needs 1", args_length)
} else {
// Search locally for corresponding Membre
membre, err := readMembre(args[0])
if err != nil {
log.Printf("[e] %s", err)
}
membre_exists := (membre.ID != 0)
if membre_exists {
log.Fatal("[e] Membre is already in the bottin-agenda database")
} else {
log.Println("[i] Membre not already in bottin-agenda, confirming existence with bottin")
// Search in bottin for corresponding Membre
membre_bottin, err := readMembreBottin(args[0])
if err != nil {
log.Fatalf("[e] %s", err)
}
membre_bottin_exists := (membre_bottin.ID != 0)
if membre_bottin_exists {
log.Println("[ok] Membre found in bottin")
if !check {
log.Println("[i] Adding to bottin-agenda")
membre_bottin.CreatedAt = time.Now()
membre_bottin.UpdatedAt = time.Now()
// Add to bottin-agenda database
data.InsertMembre(&membre_bottin)
} else {
log.Fatal("[i] Skipping insert because of --check flag")
}
} else {
log.Fatal("[e] Membre does not exist in bottin database")
}
}
}
},
}
func init() {
rootCmd.AddCommand(scanCmd)
// check
scanCmd.PersistentFlags().BoolVar(
&check, "check", false,
"Do not write anything to database.")
}
func updateFlagsBottin() {
protocol = viper.GetString("bottin.protocol")
host = viper.GetString("bottin.host")
port = viper.GetInt("bottin.port")
username = viper.GetString("bottin.username")
password = viper.GetString("bottin.password")
}
func readMembre(num_etud string) (data.Membre, error) {
data.OpenDatabase()
data.MigrateDatabase()
membre, err := data.ReadMembre(num_etud)
if err != nil {
return membre, err
}
return membre, nil
}
func readMembreBottin(num_etud string) (data.Membre, error) {
updateFlagsBottin()
membre := data.Membre{}
request := fmt.Sprintf("%s://%s:%s@%s:%d/v1/membre/%s", protocol, username, password, host, port, num_etud)
response, err := http.Get(request)
if err != nil {
return membre, err
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return membre, err
}
err = json.Unmarshal([]byte(body), &membre)
if err != nil {
return membre, err
}
return membre, nil
}