package deployers import ( "context" "fmt" "path/filepath" "github.com/rs/zerolog/log" "gitea.thegux.fr/hmdeploy/connection" "gitea.thegux.fr/hmdeploy/models" ) type NginxDeployer struct { conn connection.IConnection project *models.Project archivePath string chDone chan struct{} } var _ IDeployer = (*NginxDeployer)(nil) func NewNginxDeployer(netInfo *models.HMNetInfo, project *models.Project) (NginxDeployer, error) { var nd NginxDeployer conn, err := connection.NewSSHConn(netInfo.IP.String(), netInfo.SSH.User, netInfo.SSH.Port, netInfo.SSH.PrivKey) if err != nil { return nd, err } nd.conn = &conn nd.project = project nd.chDone = make(chan struct{}, 1) return nd, nil } func (nd *NginxDeployer) close(ctx context.Context) error { return nd.conn.Close() } func (nd *NginxDeployer) clean(ctx context.Context) (err error) { _, err = nd.conn.Execute("rm -f " + nd.project.Name + ".conf") return } func (nd *NginxDeployer) setDone() { nd.chDone <- struct{}{} } func (nd *NginxDeployer) Done() <-chan struct{} { return nd.chDone } func (nd *NginxDeployer) Clear(ctx context.Context) error { log.Debug().Msg("clearing nginx deployment...") if err := nd.clean(ctx); err != nil { log.Err(err).Msg("unable to clean nginx conf remotly") } if err := nd.close(ctx); err != nil { log.Err(err).Msg("unable to close nginx conn") } log.Debug().Msg("clear nginx deployment done") return nil } func (nd *NginxDeployer) Build(ctx context.Context) error { select { case <-ctx.Done(): nd.setDone() return fmt.Errorf("%w, nginx close ssh conn skipped", ErrContextDone) default: } nginxPath := filepath.Join(nd.project.Dir, filepath.Base(nd.project.Deps.NginxFile)) nginxConf := nd.project.Name + ".conf" log.Info().Str("nginx", nginxConf).Msg("transfering nginx conf...") if err := nd.conn.CopyFile(nginxPath, nginxConf); err != nil { nd.setDone() return err } log.Info().Str("nginx", nginxConf).Msg("nginx conf transfered with success") return nil } func (nd *NginxDeployer) Deploy(ctx context.Context) (err error) { defer nd.setDone() select { case <-ctx.Done(): return fmt.Errorf("%w, nginx close ssh conn skipped", ErrContextDone) default: } nginxConf := nd.project.Name + ".conf" log.Info().Str("nginx", nginxConf).Msg("deploying nginx conf...") _, err = nd.conn.Execute( fmt.Sprintf( "cp %s /etc/nginx/sites-available && ln -sf /etc/nginx/sites-available/%s /etc/nginx/sites-enabled/%s", nginxConf, nginxConf, nginxConf, ), ) log.Info().Str("nginx", nginxConf).Msg("nginx conf successfully deployed") return err }