---
version: '3'

vars:
  CRYPT_LABEL: '{{if .CRYPT_LABEL}}{{.CRYPT_LABEL}}{{else}}secret{{end}}'
  DISK_PATH: '{{if .DISK_PATH}}{{.DISK_PATH}}{{else}}{{.CLI_ARGS}}{{end}}'
  PARTITION_SIZE: '{{if .PARTITION_SIZE}}{{.PARTITION_SIZE}}{{else}}+25M{{end}}'

env:
  GNUPGHOME:
    sh: echo "$HOME/.gnupghome"

tasks:
  encrypt:create:
    summary: |
      # Encrypt a Disk (USB, etc.)

      This task will encrypt a disk (like a USB drive) as a single partition using
      the full disk space.

      **Usage example:**

      ```shell
      task security:disk:encrypt -- /dev/mmcblk0
      ```

      You can find the path of the USB / storage medium to pass to the CLI command
      by running `fdisk -l`.
    vars:
      DISK_LABEL: '{{if .DISK_LABEL}}{{.DISK_LABEL}}{{else}}gpg{{end}}'
      PARTITION_NUMBER: '{{if .PARTITION_NUMBER}}{{.PARTITION_NUMBER}}{{else}}1{{end}}'
    cmds:
      - sudo dd if=/dev/urandom of={{.DISK_PATH}} bs=4M status=progress
      - echo -e "o\nn\np\n{{.PARTITION_NUMBER}}\n{{.PARTITION_SIZE}}\nw" | sudo fdisk {{.DISK_PATH}}
      - echo -e "${MASTER_KEY}\n${MASTER_KEY}" | sudo cryptsetup -q luksFormat {{.DISK_PATH}}{{.PARTITION_NUMBER}}
      - echo -e "${MASTER_KEY}" | sudo cryptsetup -q luksOpen {{.DISK_PATH}}{{.PARTITION_NUMBER}} {{.CRYPT_LABEL}}
      - sudo mkfs.ext2 /dev/mapper/{{.CRYPT_LABEL}} -L {{.DISK_LABEL}}
      - sudo cryptsetup luksClose {{.CRYPT_LABEL}}

  encrypt:mount:
    vars:
      PARTITION_NUMBER: '{{if .PARTITION_NUMBER}}{{.PARTITION_NUMBER}}{{else}}1{{end}}'
    cmds:
      - echo -e "${MASTER_KEY}" | sudo cryptsetup -q luksOpen {{.DISK_PATH}}{{.PARTITION_NUMBER}} {{.CRYPT_LABEL}}
      - sudo mkdir /mnt/gpg-encrypted-storage
      - sudo mount /dev/mapper/{{.CRYPT_LABEL}} /mnt/gpg-encrypted-storage

  encrypt:unmount:
    cmds:
      - sudo umount /mnt/gpg-encrypted-storage
      - sudo cryptsetup luksClose {{.CRYPT_LABEL}}

  unencrypted:create:
    vars:
      PARTITION_NUMBER: '{{if .PARTITION_NUMBER}}{{.PARTITION_NUMBER}}{{else}}2{{end}}'
    cmds:
      - echo -e "o\nn\np\n{{.PARTITION_NUMBER}}\n{{.PARTITION_SIZE}}\nw" | sudo fdisk {{.DISK_PATH}}
      - sudo mkfs.ext2 {{.DISK_PATH}}{{.PARTITION_NUMBER}}

  unencrypted:mount:
    vars:
      PARTITION_NUMBER: '{{if .PARTITION_NUMBER}}{{.PARTITION_NUMBER}}{{else}}2{{end}}'
    cmds:
      - sudo mkdir /mnt/gpg-public
      - sudo mount {{.DISK_PATH}}{{.PARTITION_NUMBER}} /mnt/gpg-public

  unencrypted:unmount:
    cmds:
      - sudo umount /mnt/gpg-public
