package main

import (
	"log"
	"os"

	cfsslconfig "github.com/cloudflare/cfssl/config"
)

func migrateSecrets() {
	if _, err := os.Stat(secretDataPath()); err != nil {
		if os.IsNotExist(err) {
			return
		}

		log.Print("not migrating old secrets: ", err)

		return
	}

	log.Print("migrating old secrets")

	log := log.New(log.Default().Writer(), "secrets migration: ", log.Flags()|log.Lmsgprefix)

	// load secrets
	cfg, err := readConfig()
	if err != nil {
		log.Fatal(err)
		return
	}

	var sslCfg *cfsslconfig.Config

	if len(cfg.SSLConfig) == 0 {
		sslCfg = &cfsslconfig.Config{}
	} else {
		sslCfg, err = cfsslconfig.LoadConfig([]byte(cfg.SSLConfig))
		if err != nil {
			return
		}
	}

	secretData, err := loadSecretData(sslCfg)
	if err != nil {
		log.Fatal(err)
		return
	}

	for clusterName, cluster := range secretData.clusters {
		for k, v := range cluster.Tokens {
			err = clusterTokens.Put(clusterName+"/"+k, v)
			if err != nil {
				log.Fatal(err)
				return
			}
		}

		for k, v := range cluster.Passwords {
			err = clusterPasswords.Put(clusterName+"/"+k, v)
			if err != nil {
				log.Fatal(err)
				return
			}
		}

		for caName, ca := range cluster.CAs {
			clusterCAs.Put(clusterName+"/"+caName, CA{Key: ca.Key, Cert: ca.Cert})

			for signedName, signed := range ca.Signed {
				err = clusterCASignedKeys.Put(clusterName+"/"+caName+"/"+signedName, *signed)
				if err != nil {
					log.Fatal(err)
				}
			}
		}

		for hostName, pairs := range cluster.SSHKeyPairs {
			err = sshHostKeys.Put(hostName, pairs)
			if err != nil {
				log.Fatal(err)
			}
		}
	}

	if err := os.Rename(secretDataPath(), secretDataPath()+".migrated"); err != nil {
		log.Fatal("failed to rename migrated secrets: ", err)
	}
}
