CloudInitScriptConveter.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace ModulesGarden\ProxmoxAddon\App\Services;
  3. use ModulesGarden\ProxmoxAddon\App\Models\CloudInitScript;
  4. use ModulesGarden\ProxmoxAddon\App\Models\Snippet;
  5. use ModulesGarden\ProxmoxAddon\App\Models\VmModel;
  6. use ModulesGarden\ProxmoxAddon\App\Repositories\ServerConfigurationRepository;
  7. use ModulesGarden\ProxmoxAddon\Core\Traits\Smarty;
  8. use ModulesGarden\ProxmoxAddon\Core\UI\Traits\WhmcsParams;
  9. use function ModulesGarden\ProxmoxAddon\Core\Helper\sl;
  10. class CloudInitScriptConveter
  11. {
  12. use Smarty;
  13. use WhmcsParams;
  14. use ApiService;
  15. /**
  16. * @var CloudInitScript
  17. */
  18. protected $cloudInitScript;
  19. /**
  20. * @var ServerConfigurationRepository
  21. */
  22. protected $serverConfiguration;
  23. /**
  24. * @var VmModel|null
  25. */
  26. protected $vmModel;
  27. /**
  28. * CloudInitScriptConveter constructor.
  29. * @param CloudInitScript $cloudInitScript
  30. */
  31. public function __construct(CloudInitScript $cloudInitScript, ServerConfigurationRepository $serverConfiguration, $vmModel =null)
  32. {
  33. $this->cloudInitScript = $cloudInitScript;
  34. $this->serverConfiguration = $serverConfiguration;
  35. $this->vmModel = $vmModel;
  36. }
  37. /**
  38. * @return Snippet
  39. */
  40. public function convert(){
  41. if(!$this->serverConfiguration->snippetDirectory){
  42. throw new \InvalidArgumentException("Snippet Directory is empty");
  43. }
  44. $script = html_entity_decode($this->cloudInitScript->script, ENT_QUOTES);
  45. $params = sl('whmcsParams')->getWhmcsParams();
  46. $params['passwordHash'] = Utility::passwordHash($params['password']);
  47. if($this->vmModel instanceof VmModel){
  48. //load ip addresses
  49. $this->vmModel->ipv4Addresses;
  50. $this->vmModel->ipv6Addresses;
  51. $params['vm'] = $this->vmModel->toArray();
  52. //password decode
  53. $params['vm']['password'] = $this->vmModel->getPassword();
  54. $params['vm']['passwordHash'] = Utility::passwordHash($params['vm']['password']);
  55. $filename = sprintf("userconfig-%s-%s.yaml",$this->getWhmcsParamByKey('serviceid'), $this->vmModel->id);
  56. }else{//vps
  57. $filename = sprintf("userconfig-%s.yaml",$this->getWhmcsParamByKey('serviceid'));
  58. }
  59. $content = $this->getSmarty()->fetchString($script, $params);
  60. return new Snippet($this->serverConfiguration->snippetDirectory,$filename, $content);
  61. }
  62. }