package main

import (
	"bytes"
	"fmt"
	"log"
	"os"
	"strings"
	"time"
	"canguidev.fr/pvnet/function"
	simplyssh "canguidev.fr/pvnet/simply-ssh"
	"github.com/TwiN/go-choice"
	"github.com/joho/godotenv"
	"github.com/pkg/sftp"
)

func main() {
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}
	var pathSsh string = os.Getenv("PATH_SSH")
	var pathConfigSsh = os.Getenv("PATH_SSH_CONF")
	var pathExcel string = os.Getenv("PATH_FOLDER_EXEL")
	var mysqlUser string
	var mysqlPswd string
	var pathSaveSql string
	var nameBase string
	var sheetSelect string=os.Getenv("SHEET_SELECT")
	// Chargement de la liste des hosts du fichier config ssh
	d := simplyssh.GetHost(pathConfigSsh)
	var s []string
	for _, host := range d {
		fmt.Println(host)
		s = append(s, string(host.Id)+" "+host.Host)
	}
	// selectionne du host
	choice, index, err := gochoice.Pick(
		"Sélectionner un vhost de connection?\nChoix:",
		s,
	)
	selectHost := choice
	if err != nil {
		fmt.Println("You didn't select anything!", err)
	} else {
		for _, host := range d {
			// for sur les hosts et break sur le host selectionner
			if host.Id == uint(index) {
				fmt.Println("debut de connection")
				// connection en ssh avec la clée et les informations du fichier config
				client := simplyssh.Connect(pathSsh, host.HostName, host.Port, host.User)
				command := "mkdir backup"
				defer client.Close()

				// Ouverture d une session pour excecuté la commande
				session, err := client.NewSession()
				if err != nil {
					log.Fatal("Failed to create session: ", err)
				}
				defer session.Close()
				// initialisation du buffer pour recupere les infos reçu de l' hôte
				var b bytes.Buffer
				session.Stdout = &b
				//exceution de la commande
				if err := session.Run(command); err != nil {
					fmt.Println("Dossier existe dejà")
					// Fermez donc cette session
					session.Close()

					// Créez une nouvelle session pour exécuter le backup

					_, index, err := gochoice.Pick(
						"What do you want to do?\nPick:",
						[]string{
							"Backup sql and download",
							"Backup site",
							"Check serveur apache",
						},
					)
					if err != nil {
						fmt.Println("You didn't select anything!")
						return
					}
					if index == 0 {
						excel := function.ReadExcel(pathExcel,sheetSelect)
						// Parcourir les résultats d'Excel
						for _, value := range excel {
							sessionBackup, err := client.NewSession()
							if err != nil {
								log.Fatal("Failed to create session for backup: ", err)
							}
							defer sessionBackup.Close()
							fmt.Println("--------------------------")
							for key, val := range value {
								if strings.Compare(val, selectHost) == 1 {
									switch key {
									case "path_save_sql":
										pathSaveSql = val
									case "path_save_site":
										// pathSaveSite = v
									case "mysql_login":
										mysqlUser = val
									case "mysql_pasw":
										mysqlPswd = val
									case "name_base":
										nameBase = val
									}
								}
							}
							fmt.Println("--------------------------")
							fmt.Println("MySQL User:", mysqlUser)
							fmt.Println("MySQL Password:", mysqlPswd)
							fmt.Println("Path Save SQL:", pathSaveSql)
							fmt.Println("Name Base:", nameBase)
							fmt.Println("--------------------------")
							//log.Fatal("stop julien")
							currentTime := time.Now()
							formattedTime := currentTime.Format("20060102_150405")

							filename := "backup/" + nameBase + "_" + formattedTime + ".sql"
							commandBackup := "mysqldump -u " + mysqlUser + " -p'" + mysqlPswd + "' " + nameBase + " > " + filename

							// Maintenant on utilise la sessionBackup pour exécuter la commande du backup
							if err := sessionBackup.Run(commandBackup); err != nil {
								log.Fatal("Failed to run commandBackup: " + err.Error())
							}
							fmt.Println("backup ok")
							if client == nil {
								log.Fatal("Client SSH non initialisé")
							}
							sftpClient, err := sftp.NewClient(client)
							if err != nil {
								log.Fatal("Erreur connection: ", err)
							}
							defer sftpClient.Close()
							currentTime2 := time.Now()
							formattedTime2 := currentTime2.Format("20060102_150405")
							filename2 := nameBase+"_" + formattedTime2 + ".sql"
							err = simplyssh.DownloadFile(sftpClient, filename, pathSaveSql+filename2)
							if err != nil {
								log.Fatal("Erreur lors du téléchargement: ", err)
							}
							fmt.Println("Téléchargement terminé")

						}

					}
					if index == 1 {
						excel := function.ReadExcel(pathExcel,sheetSelect)
						// Parcourir les résultats d'Excel
						var pathSaveSite string
						var serveurPathSite string
						for _, value := range excel {
							sessionBackup, err := client.NewSession()
							if err != nil {
								log.Fatal("Failed to create session for backup: ", err)
							}
							defer sessionBackup.Close()
							fmt.Println("--------------------------")
							for key, val := range value {
								if strings.Compare(val, selectHost) == 1 {
									switch key {
									case "path_save_site":
										pathSaveSite = val
									case "path_site_serveur":
										serveurPathSite = val
										
									}
									
								}
							}
							fmt.Println("--------------------------")
							
							fmt.Println("Path save site:", pathSaveSite)
							fmt.Println("--------------------------")
							//log.Fatal("stop julien")

						
							sftpClient, err := sftp.NewClient(client)
							if err != nil {
								log.Fatal("Erreur connection: ", err)
							}
							defer sftpClient.Close()
							err = simplyssh.DownloadDirectory(sftpClient,serveurPathSite , pathSaveSite)
							if err != nil {
								log.Fatal("Erreur lors du téléchargement: ", err)
							}
							fmt.Println("Téléchargement terminé")

						}
					}

				}
				fmt.Println(b.String())

			}
		}
		fmt.Printf("You have selected: '%s', which is the index %d\n", choice, index)
	}
}
