SimpleDockerApps.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
########## PRIVATE FUNCTIONS ##########
#######################################

function ConvertFrom-JsonWithComments {
  <#
  .SYNOPSIS
    Converts a .jsonc string to a JsonObject.
  .DESCRIPTION
    This command converts a Json with Comments string representation to a JsonObject.
  .INPUTS
    System.String
  .OUTPUTS
    System.Object
  #>

  param (
    # Input object of type string which will be converted from JSON
    [Parameter(Mandatory, ValueFromPipeline, Position = 0)]
    [AllowEmptyString()]
    [string]$InputObject
  )
  
  if ( $PSVersionTable.PSVersion.Major -gt 5 ) {
    return $Input | ConvertFrom-Json
  }
  else {
    $Input = ($Input -replace '(?m)(?<=^([^"]|"[^"]*")*)//.*' -replace '(?ms)/\*.*?\*/')
    return $Input | ConvertFrom-Json
  }
}

function Test-SdaNetworkStatus {
  <#
  .SYNOPSIS
    Checks if requested network already exists
  .DESCRIPTION
    This command wil query information about networks via docker cli and checks if requested network already exists
  .INPUTS
    None. You cannot pipe objects to this command
  .OUTPUTS
    Boolean
  #>

  param (
    # Name of the network
    [string]$Name = (Get-SdaConfig).defaultNetwork,
    # Only return, no output to console
    [switch]$JustConfirm = $false
  )
  $status = docker network ls --filter "name=^$Name$" --format '{{.Name}}'
  if ($null -ne $status) {
    if (-not $JustConfirm) {
      Write-Host "Network '$Name' exists, everything looks alright."
    }
    $true
  }
  else {
    if (-not $JustConfirm) {
      Write-Host "Network '$Name' doesn't exist..."
    }
    $false
  }
}

function Invoke-SolrCoreCreation {
  param (
    $User,
    $Prefix,
    $Name
  )
  ### SOLR specific
  # To use Solr so called 'core' needs to be created
  docker exec -it --user=$User "$Prefix-$Name" bin/solr create_core -c defaultcore
  if ($?) { 
    Write-Output "core created with name 'defaultcore'"
  }
  else {
    Write-Error "Error creating core"
    break
  }
}

function Get-Confirmation {
  <#
  .SYNOPSIS
    Gets confirmation from user with custom message
  .DESCRIPTION
    This command will get confirmation from user with custom message and returns true or false
  .EXAMPLE
    PS C:\> Get-Confirmation -Message "Are you sure?"
      Are you sure? (Y/n)
      True
  .INPUTS
    None. You cannot pipe objects to this command
  .OUTPUTS
    Boolean
  #>

  param (
    # Custom message you want to confirm
    [string]$Message = "Are you sure you want to proceed?"
  )
  $confirmation = Read-Host "$Message (Y/n)"
  switch -Regex ($confirmation) {
    '[Nn]' { $false }
    Default { $true }
  }
}

function New-SdaDockerCommand {
  <#
  .SYNOPSIS
    Constructs docker command string
  .DESCRIPTION
    This command will get confirmation from user with custom message and returns true or false
  .EXAMPLE
    $service.docker | New-SdaDockerCommand -Name mssql -Prefix sda -Network sda -Version latest -Pass Start123++
      docker create --net sda --name sda-mssql --ulimit nofile=262144:262144 -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=Start123++' -e 'MSSQL_PID=Express' -v sda-mssql-data:/var/opt/mssql -p 1433:1433 mcr.microsoft.com/mssql/server:latest
  .INPUTS
    PSCustomObject
      Docker section from specific service configuration
  .OUTPUTS
    String
  #>

  param (
    # Docker section from specific service configuration
    [Parameter(Mandatory, Position = 0, ValueFromPipeline)]
    [PSCustomObject]$DockerConfig,
    # Name of service
    [string]$Name,
    # Prefix from configuration
    [string]$Prefix,
    # Name of network to attach to
    [string]$Network,
    # Version of docker image
    [string]$Version,
    # Password
    [string]$Pass
  )

  # Base command
  $command = "docker create --net $Network --name $Prefix-$Name $($DockerConfig.AdditionalDockerArguments -join " ")"

  # Add Environment Variables (if any)
  if ($DockerConfig.EnvVars.Length -gt 0) {
    $DockerConfig.EnvVars | ForEach-Object {
      $command += " -e ""$(Format-SdaPlaceholder -Name PASSWORD -Source $_ -Value $Pass)"""
    }
  }

  # Add Volumes (if any)
  if ($DockerConfig.Volumes.Length -gt 0) {
    $DockerConfig.Volumes | ForEach-Object {
      $command += " -v $Prefix-$(Format-SdaPlaceholder -Name NAME -Source $_.Source -Value $Name):$($_.Target)"
    }
  }

  # Add Ports (if any)
  if ($DockerConfig.PortMappings.Length -gt 0) {
    $DockerConfig.PortMappings | ForEach-Object {
      $command += " -p $($_.host):$($_.container)"
    }
  }

  # Add Image Info + Custom App Command
  $command += " $($DockerConfig.ImageName):$($Version) $($DockerConfig.CustomAppCommands)"

  # Return command for execution
  $command
}

function Get-SdaConfig {
  <#
  .SYNOPSIS
    Gets configuration object
  .DESCRIPTION
    This command will read the json configuration and converts it to Object
  .OUTPUTS
    PSCustomObject
      Powershell object representation of json configuration
  #>

  if (Test-Path $PSScriptRoot/config.json) {
    Write-Output (Get-Content $PSScriptRoot/config.json -Raw | ConvertFrom-JsonWithComments)
  }
  else {
    Throw "Config file does not exist"
  }
}

function Get-SdaServiceFromConfig {
  <#
  .SYNOPSIS
    Gets service information from configuration object
  .DESCRIPTION
    This command will return a specific service from configuration object
  .OUTPUTS
    PSCustomObject
      Powershell object representation of particular service from configuration
  #>

  param (
    # Configuration object
    [Parameter(Position = 0, Mandatory, ValueFromPipeline)]
    [System.Object]$Config,
    # Name of service
    [string]$Name
  )
  return $Config.services | Where-Object { $_.Name -eq "$Name" }
}

function Write-SdaDefaultWarning {
  <#
  .SYNOPSIS
    Writes a custom message to standard output
  .DESCRIPTION
    This command returns a custom message to warn user about important action
  .OUTPUTS
    None. This command does not generate any output.
  #>

  param (
    # Command to run again with
    [string]$Command,
    # Provided value which was used
    [string]$Value,
    # Output name of a service from configuration ($service.OutputName)
    [string]$Name,
    # Action we are doing
    [string]$Action = "Creating",
    # Type of a warning
    [string]$Type = "password"
  )
  Write-Output "$Action '$Name' in Docker container using the default $Type '$Value'"
  Write-Output "For custom $Type run again with: '$Command'"
  if ($Type -eq "password" -and $Action -eq "Creating") {
    Write-Output "Password must be strong, otherwise docker fails to create container"
  }
}

function Format-SdaPlaceholder {
  <#
  .SYNOPSIS
    Replace {PLACEHOLDER} in a string with a value
  .DESCRIPTION
    This command replaces a placeholder in a string with actual value, if no placeholder return original string
  .EXAMPLE
    PS C:\> Format-SdaPlaceholder "Hello {NAME}" -Name NAME -Value "Stefan"
      Hello Stefan
  .EXAMPLE
    PS C:\> "Hello {NAME}, nice to see you" | Format-SdaPlaceholder -Name NAME -Value "Stefan"
      Hello Stefan, nice to see you
  .INPUTS
    String
  .OUTPUTS
    String
  #>

  param(
    # Source string in which replacement will be performed
    [Parameter(Mandatory, Position = 0, ValueFromPipeline)]
    [AllowEmptyString()]
    [string]$Source,
    # Name of a placeholder (e.g. NAME for a {NAME} placeholder)
    [string]$Name,
    # Value to replace with
    [string]$Value
  )

  if ($Source -match "\{$Name\}") {
    return $Source -replace "\{$Name\}", "$Value"
  }
  else {
    return $Source
  }
}

function Get-SdaServicesAvailable {
  <#
  .SYNOPSIS
    Lists all available services
  .DESCRIPTION
    Lists all available services that are configured
  .INPUTS
    None. You cannot pipe objects to this command
  .OUTPUTS
    PSCustomObject
  #>

  (Get-SdaConfig).services | ForEach-Object { [PSCustomObject]@{SDA = $_.OutputName ; Name = $_.Name } }
}

function Get-SdaServicesCreated {
  <#
  .SYNOPSIS
    Lists all created services
  .DESCRIPTION
    Lists all created services that are available in docker
  .INPUTS
    None. You cannot pipe objects to this command
  .OUTPUTS
    PSCustomObject
  #>

  $prefix = (Get-SdaConfig).prefix
  $services = docker container ls -a -f "name=$prefix-" --format '{{json .}}' | ConvertFrom-Json
  foreach ($service in $services) {
    $output = [PSCustomObject]@{
      Name          = $service.Names.Substring($prefix.Length + 1)
      ContainerName = $service.Names
      ID            = $service.ID
      Image         = $service.Image
      Networks      = $service.Networks
      Ports         = $service.Ports
      Status        = $service.Status
    }

    Write-Output $output
  }
}

function Get-SdaServicesRunning {
  <#
  .SYNOPSIS
    Lists all running services
  .DESCRIPTION
    Lists all running services that are available in docker
  .INPUTS
    None. You cannot pipe objects to this command
  .OUTPUTS
    PSCustomObject
  #>

  Get-SdaServicesCreated | Where-Object { $_.Status -match "^Up.*" }
}

function Get-SdaServicesStopped {
  <#
  .SYNOPSIS
    Lists all stopped services
  .DESCRIPTION
    Lists all stopped services that are available in docker
  .INPUTS
    None. You cannot pipe objects to this command
  .OUTPUTS
    PSCustomObject
  #>

  Get-SdaServicesCreated | Where-Object { $_.Status -notmatch "^Up.*" }
}

########## PUBLIC FUNCTIONS ###########
#######################################

## INFO cmdlets

function Get-SdaConfigFileLocation {
  <#
  .SYNOPSIS
    Returns a location to a default config file.
  .DESCRIPTION
    Returns a location to default config file that is required for this module to function
  .EXAMPLE
    PS C:\> Get-SdaConfigFileLocation
     
    Returns a location to a default config file.
  .OUTPUTS
    String
  #>

  Write-Output (Join-Path $PSScriptRoot "config.json")
}

function Get-SdaConfigDetails {
  <#
  .SYNOPSIS
    Returns json representation of a configuration, either general, or of specific service
  .DESCRIPTION
    Returns json representation of a configuration, either general, or of specific service
  .EXAMPLE
    PS C:\> Get-SdaConfigDetails
     
    Returns json representation of a configuration, either general, or of specific service
  .INPUTS
    None. You cannot pipe objects to this command
  .OUTPUTS
    String
  #>

  param (
    # Name of a service
    [string]$Name
  )
  $config = Get-SdaConfig
  if ($Name) {
    $server = $config | Get-SdaServiceFromConfig -Name $Name
    if ($null -ne $server) {
      $server | ConvertTo-Json -Depth 3
    }
    else {
      Write-Error "Specified server '$Name' is not available yet."
    }
  }
  else {
    Write-Output @{
      Prefix          = $config.prefix
      DefaultNetwork  = $config.defaultNetwork
      DefaultPassword = $config.defaultPassword
    } | ConvertTo-Json -Depth 3
  }
}

## IMAGE management
function Remove-SdaImages {
  <#
  .SYNOPSIS
    Removes dangling docker images
  .DESCRIPTION
    Removes all images that are not associated with other resources (so called dangling images)
    Images can be downloaded again in case you remove more than you want.
  .EXAMPLE
    PS C:\> Get-SdaImages
     
    Query existing docker images, compare them with config and removes only those that match
  .EXAMPLE
    PS C:\> Get-SdaImages -Dangling
     
    Removes all dangling images
  .INPUTS
    None. You cannot pipe objects to this command
  .OUTPUTS
    None. This command does not generate any output.
  #>

  param(
    # Specify if remove only dangling
    [switch]$Dangling
  )
  if ($Dangling) {
    if (Get-Confirmation -Message "Are you sure you want to remove all dangling images?") {
      $danglingImages = docker images -f "dangling=true" -q
      if ($null -ne $danglingImages) {
        docker rmi -f $danglingImages
      }
      else {
        Write-Host "No dangling images were found"
      }
      
    }
  }
  else {
    if (Get-Confirmation -Message "Are you sure you want to remove all images?") {
      $dockerImages = docker images --format '{{json .}}' | ConvertFrom-Json
      foreach ($image in $dockerImages) {
        $service = (Get-SdaConfig).services | Where-Object { $_.docker.imageName -eq $image.Repository }
        if ($service.Length -gt 0) {
          docker rmi -f $image.ID | Out-Null
          if ($?) {
            Write-Host "Image '$($image.ID)' was removed"
          }
        }
      }
    }
  }
  
}

## NETWORK management

function New-SdaNetwork {
  <#
  .SYNOPSIS
    Creates new docker network
  .DESCRIPTION
    Creates new docker network of driver type 'bridge'
  .EXAMPLE
    PS C:\> Get-SdaNetwork my-network
     
    Creates my-network of driver type 'bridge'
  .INPUTS
    None. You cannot pipe objects to this command
  .OUTPUTS
    None. This command does not generate any output.
  #>

  param (
    # Name of a network to create (Defaults to network specified in config)
    $Name = (Get-SdaConfig).DefaultNetwork
  )
  if (-not (Test-SdaNetworkStatus -Name $Name -JustConfirm)) {
    if (Get-Confirmation -Message "Are you sure you want to create network '$Name'?") {
      docker network create $Name
      if ($?) {
        Write-Host "Network successfuly created."
      }
    }
    else {
      Write-Host "Skipping network creation..."
    }
  }
}

## SERVICE management

function Get-SdaService {
  <#
  .SYNOPSIS
    Get information about specific service, or list of running, available, stopped and created services
  .DESCRIPTION
    Get information about specific service, or list of running, available, stopped and created services
    Defaults to list running services if no Name, or one of [Available, Running, Stopped, Created] is given
  .EXAMPLE
    PS C:\> Get-SdaService -Name mssql
    Name Value
    ---- -----
    Status running
    Container sda-mssql
    Name mssql
 
 
  .EXAMPLE
    PS C:\> Get-SdaService # Defaults to list running services
    Name Value
    ---- -----
    Ports 0.0.0.0:1433->1433/tcp
    Image mcr.microsoft.com/mssql/server:latest
    ID 243a8ebb4118
    Status Up 51 minutes
    Name sda-mssql
    Networks simple-docker-apps
 
 
  .EXAMPLE
    PS C:\> Get-SdaService -Running
    Name Value
    ---- -----
    Ports 0.0.0.0:1433->1433/tcp
    Image mcr.microsoft.com/mssql/server:latest
    ID 243a8ebb4118
    Status Up 51 minutes
    Name sda-mssql
    Networks simple-docker-apps
 
 
  .EXAMPLE
    PS C:\> Get-SdaService -Available
    Name Value
    ---- -----
    MS SQL mssql
    PostgreSQL postgres
 
 
  .EXAMPLE
    PS C:\> Get-SdaService -Created
    Name Value
    ---- -----
    Ports 0.0.0.0:1433->1433/tcp
    Image mcr.microsoft.com/mssql/server:latest
    ID 243a8ebb4118
    Status Up 54 minutes
    Name sda-mssql
    Networks simple-docker-apps
          
    Ports 0.0.0.0:5432->5432/tcp
    Image postgres:11
    ID 75eb3b089d5b
    Status Exited (255) 2 hours ago
    Name sda-postgres
    Networks simple-docker-apps
 
 
  .EXAMPLE
    PS C:\> Get-SdaService -Stopped
    Name Value
    ---- -----
    Ports 0.0.0.0:5432->5432/tcp
    Image postgres:11
    ID 75eb3b089d5b
    Status Exited (255) 2 hours ago
    Name sda-postgres
    Networks simple-docker-apps
 
 
  .INPUTS
    None. You cannot pipe objects to this command
  .OUTPUTS
    PSCustomObject
      For no arguments, or -Name, -Running, -Stopped, -Created
    object[]
      For -Available
  #>

  param (
    # Name of service, when specified, other switches are ignored
    [string]$Name,
    # Switch to list all available services
    [switch]$Available,
    # Switch to list all running services
    [switch]$Running,
    # Switch to list all stopped services
    [switch]$Stopped,
    # Switch to list all created services
    [switch]$Created,
    # Switch to suppress Write-Error and return only $null. Usefull in scripting
    [switch]$SupressOutHost
  )
  $config = Get-SdaConfig
  if ($Name.Length -gt 0) {
    $service = $config | Get-SdaServiceFromConfig -Name $Name
    if ($null -eq $service) {
      Write-Output "The SDA service '$Name' does not exist, here is a list of all available services:"
      Get-SdaServicesAvailable
      break;
    }
    else {
      $containerName = "$($config.prefix)-$($service.Name)"
      #$containerName = "$($service.Name)"
      $info = docker container inspect $containerName --format '{{json .State}}' 2>$null | ConvertFrom-Json
      if ($null -ne $info) {
        [PSCustomObject]@{
          Name      = $service.Name
          Container = $containerName
          Status    = $info.Status
        }
      }
      else {
        if (-not ($SupressOutHost)) {
          Write-Host "ERROR: Container '$containerName' doesn't exist"
        }
        $null
      }
    }
  }
  elseif ($Available) {
    Get-SdaServicesAvailable
  }
  elseif ($Running) {
    Get-SdaServicesRunning
  }
  elseif ($Created) {
    Get-SdaServicesCreated
  }
  elseif ($Stopped) {
    Get-SdaServicesStopped
  }
  else {
    Get-SdaServicesRunning
  }
}

function Start-SdaService {
  <#
  .SYNOPSIS
    Starts SDA service
  .DESCRIPTION
    Starts SDA service
  .EXAMPLE
    PS C:\> Start-SdaService mssql
     
    Starts service 'mssql'
  .EXAMPLE
    PS C:\> Get-SdaService -Stopped | Start-SdaService
     
    Starts all stopped SDA services
  .INPUTS
    PSCustomObject
      Object returned from Get-Service
  .OUTPUTS
    PSCustomObject
      Object with new status of a service
  #>

  param (
    # Service name
    [Parameter(Position = 0, ValueFromPipelineByPropertyName, Mandatory = $true)]
    [string]$Name
  )
  process {
    $info = Get-SdaService -Name $Name
    if ($null -ne $info) {
      if ($info.Status -ne "running") {
        docker start $info.Container | Out-Null
        Get-SdaService -Name $Name
      }
      else {
        $info
      }
    }
  }
}

function Stop-SdaService {
  <#
  .SYNOPSIS
    Stops SDA service
  .DESCRIPTION
    Stops SDA service
  .EXAMPLE
    PS C:\> Stop-SdaService mssql
     
    Stops service 'mssql'
  .EXAMPLE
    PS C:\> Get-SdaService -Running | Stop-SdaService
     
    Stops all running SDA services
  .INPUTS
    PSCustomObject
      Object returned from Get-Service
  .OUTPUTS
    PSCustomObject
      Object with new status of a service
  #>

  param (
    # Service name
    [Parameter(Position = 0, ValueFromPipelineByPropertyName, Mandatory = $true)]
    [string]$Name,
    # Switch to kill instead of graceful shutdown
    [switch]$Kill
  )
  process {
    $info = Get-SdaService -Name $Name
    if ($null -ne $info) {
      if ($info.Status -eq "running") {
        if ($Kill) {
          docker kill $info.Container | Out-Null
          Get-SdaService -Name $Name
        }
        else {
          docker stop $info.Container -t 10 | Out-Null
          Get-SdaService -Name $Name
        }
      }
      else {
        $info
      }
    }
  }
}

function Remove-SdaService {
  <#
  .SYNOPSIS
    Removes SDA service
  .DESCRIPTION
    Removes SDA service
 
    Can also remove dangling volumes, which is destructive action and will remove all your data without possibility to recover.
  .EXAMPLE
    PS C:\> Remove-SdaService mssql
     
    Removes service 'mssql'
  .EXAMPLE
    PS C:\> Remove-SdaService mssql -Volumes
     
    Removes service 'mssql' including all related volumes
  .EXAMPLE
    PS C:\> Get-SdaService -Stopped | Remove-SdaService
     
    Removes all stopped SDA services
  .INPUTS
    PSCustomObject
      Object returned from Get-Service
  .OUTPUTS
    PSCustomObject
      Object with new status of a service
  #>

  param(
    # Service name
    [Parameter(Position = 0, ValueFromPipelineByPropertyName, Mandatory = $true)]
    [string]$Name,
    # Switch to remove also related volumes (THIS IS DESTRUCTIVE ACTION)
    [switch]$Volumes
  )
  process {
    $info = Get-SdaService -Name $Name
    if ($Volumes) {
      $msg = "Are you sure you want to remove '$Name' and all associated volumes?"
    }
    else {
      $msg = "Are you sure you want to remove '$Name'?"
    }
    if (-not (Get-Confirmation -Message $msg)) {
      break
    }
    if ($null -ne $info) {
      if ($info.Status -eq "running") {
        if ((Stop-SdaService $Name -Kill).Status -eq "exited") {
          docker container rm $info.Container
        }
      }
      else {
        docker container rm $info.Container
      }
    }
    if ($PSBoundParameters.ContainsKey("Volumes")) {
      $config = Get-SdaConfig
      Write-Host "-Volume flag detected, searching for dangling volumes..."
      $serviceVolumes = docker volume ls -f "dangling=true" -f "name=$($config.prefix)-$Name-" --format '{{json .Name}}' | ConvertFrom-Json

      # fix the type
      if ($serviceVolumes.GetType().Name -eq "String") {
        $serviceVolumes = @($serviceVolumes)
      }

      if ($serviceVolumes.Length -gt 0) {
        Write-Host "Found $($serviceVolumes.Length) volumes, attempting to remove..."
        foreach ($volume in $serviceVolumes) {
          if (-not (Get-Confirmation -Message "Are you sure you want to remove '$volume'")) {
            continue
          }
          docker volume rm $volume | Out-Null
          if ($?) {  
            Write-Output "'$volume' successfuly removed."
          }
          else {
            Write-Output "ERROR: Problem removing '$volume', manual action might be needed"
          }
        }
      }
      else {
        Write-Host "No volumes found"
      }
    }
  }
}

function New-SdaService {
  <#
  .SYNOPSIS
    Creates new service
  .DESCRIPTION
    Creates new SDA service.
    If volumes already exists it will reuse them.
  .EXAMPLE
    PS C:\> New-SdaService mssql
     
    Creates new service 'mssql' with default settings
  .EXAMPLE
    PS C:\> New-SdaService mongodb -Network custom-network -Version 3 -Pass "Start123"
     
    Creates new service 'mongodb' with custom network name, versiona and password
  .INPUTS
    None. You cannot pipe objects to this command
  .OUTPUTS
    Output (if any)
  #>

  param (
    # Service name
    [Parameter(Mandatory)]
    [string]$Name,
    # Password, will be used instead of default from config
    [string]$Pass = "",
    # Network name, will be used instead of default from config
    [string]$Network,
    # Version, will be used instead of default from config
    [string]$Version
  )
  # Get necessary configuration
  $config = Get-SdaConfig
  $service = Get-SdaServiceFromConfig -Config $config -Name $Name

  # Check if service really exists
  if ($null -eq $service) {
    Write-Output "The SDA service '$Name' does not exist, here is a list of all available services:"
    Get-SdaServicesAvailable
    break;
  }
  
  # Check if really use default password
  if ($Pass -eq "" -and $service.HasPassword) {
    Write-SdaDefaultWarning -Command "New-SdaService -Name $Name -Pass <SA_PASSWORD>" -Value $config.DefaultPassword -Name $service.outputName
    if (-not (Get-Confirmation)) { break }
  }

  # Check if requested service is already running
  $info = Get-SdaService -Name $Name -SupressOutHost
  if ($null -ne $info) {
    if (Get-Confirmation -Message "Container already exists. Do you want me to destroy it?") {
      if ((Stop-SdaService -Name $Name -Kill).Status -eq "exited") { Remove-SdaService -Name $Name }
    }
    else {
      break
    }
  }

  # Check if Network exists
  if ($Network -eq "") {
    $Network = $config.DefaultNetwork
  }
  if (-not (Test-SdaNetworkStatus -Name $Network -JustConfirm)) {
    New-SdaNetwork -Name $Network
  }

  $params = @{
    Name         = $Name
    Version      = if ($Version) { "$Version" } else { "$($service.DefaultVersion)" }
    Pass         = if ($Pass -ne "") { "$Pass" } else { "$($config.DefaultPassword)" }
    Network      = $Network
    Prefix       = $config.prefix
    DockerConfig = $service.docker
  }

  Invoke-Expression (New-SdaDockerCommand @params)
  if ($?) { 
    Write-Output "Container created"
  }
  else {
    Write-Error "Error creating container. Exiting..."
    break
  }
  $info = Start-SdaService -Name $Name
  if ($info.Status -eq "running") { 
    Write-Output "Container started"
  }
  else {
    Write-Error "Error starting container"
    break
  }

  ## SOLR specific TODO: find better place for this
  if ($Name -eq "solr") {
    Invoke-SolrCoreCreation -Name "solr" -Prefix $config.Prefix -User "solr"
  }
}

function Connect-SdaService {
  <#
  .SYNOPSIS
    Connects to a service inside the docker container
  .DESCRIPTION
    Connects to a service inside running container. It leverages the 'docker exec -it' command.
 
    Also supports opening web dashboard if url is present in config. It will be opened in default web browser, this functionality is cross-platform
  .EXAMPLE
    PS C:\> Connect-SdaService mssql
     
    Connects to service 'mssql' with default settings
  .EXAMPLE
    PS C:\> Connect-SdaService ravendb -Web
     
    Opens configured dashboard url in default browser.
  .EXAMPLE
    PS C:\> Connect-SdaService mongodb -Pass "Start123"
     
    Connects to service 'mongodb' with custom password
  .INPUTS
    None. You cannot pipe objects to this command
  .OUTPUTS
    None. This command does not generate any output
  #>

  param (
    # Service name
    [Parameter(Mandatory)]
    [string]$Name,
    # Password, will be used instead of default from config
    [string]$Pass = "",
    # Specify if open web browser instead
    [switch]$Web
  )

  # Get configuration
  $config = Get-SdaConfig
  $service = Get-SdaServiceFromConfig -Config $config -Name $Name

  # Check if service really exists
  if ($null -eq $service) {
    Write-Output "The SDA service '$Name' does not exist, here is a list of all available services:"
    Get-SdaServicesAvailable
    break;
  }

  # Check if we can connect to service via cli
  if (-not ($service.HasCliConnect)) {
    Write-Error "The SDA service '$Name' does not support CLI connection"
    break
  }

  # Check if service has url specified in config if -Web passed
  if ($Web -and (-not $service.HasWebConnect)) {
    Write-Error "The SDA service '$Name' does not support web dashboard"
    break
  }

  # Check if service is running
  $info = Get-SdaService -Name $Name
  if ($null -eq $info) {
    Write-Error "The SDA service '$Name' is not running, Please start service first with 'Start-SdaService -Name $Name'"
    break
  }

  if ($Web) {
    $url = $service.WebConnectUrl
    Write-Output "Connecting to $($service.OutputName) web interface at: '$url'"
    Write-Output "If web browser did not open automatically please open browser and paste address in manually"
    if (-not (Get-Confirmation)) {
      break
    }

    if ($IsLinux) {
      xdg-open $url
      break
    }
    elseif ($IsMacOS) {
      open $url
      break
    }
    else {
      Start-Process $url
      break
    }
  }

  if ($Pass -eq "" -and $service.HasPassword) {
    $Pass = $config.DefaultPassword
    Write-SdaDefaultWarning -Command "Connect-SdaService $Name -Pass <SA_PASSWORD>'" -Action "Connecting to" -Type "password" -Name $service.OutputName -Value $Pass
    
    if (-not (Get-Confirmation)) {
      break
    }
  }
  $cliCommand = Format-SdaPlaceholder -Name PASSWORD -Value $Pass -Source "$($service.CliConnectCommand)"
  docker exec -it "$($config.prefix)-$Name" sh -c "$cliCommand"
}