---
version: '3'

tasks:
  export:
    deps:
      - :install:software:snapcraft
    summary: |
      # Export Snapcraft Login Credentials

      This task will export an unencrypted file called `snap.login` which you can
      use to extract the macaroon/unbound_discharge/email. Once extracted, save
      them as environment variables for use with the other tasks.
    log:
      error: Error encountered while exporting `snap.login`
      start: Exporting login credentials to unencrpyted file named `snap.login`
      success: Successfully exported `snap.login` (unencrypted)
    cmds:
      - snapcraft export-login snap.login

  login:
    deps:
      - :install:software:snapcraft
    vars:
      SNAP_LOGIN_TEMPLATE: |
        [login.ubuntu.com]
        macaroon = {{env "SNAPCRAFT_MACAROON"}}
        unbound_discharge = {{env "SNAPCRAFT_UNBOUND_DISCHARGE"}}
        email = {{env "SNAPCRAFT_EMAIL"}}
    log:
      error: Error encountered while logging into Snapcraft
      start: Logging into Snapcraft
      success: Successfully logged into Snapcraft
    cmds:
      - |
        echo '{{.SNAP_LOGIN_TEMPLATE}}' > snap.login
        snapcraft login --with snap.login || rm -f snap.login
        rm -f snap.login
    preconditions:
      - '[ -n "$SNAPCRAFT_MACAROON" ]'
      - '[ -n "$SNAPCRAFT_UNBOUND_DISCHARGE" ]'
      - '[ -n "$SNAPCRAFT_EMAIL" ]'

  register:
    deps:
      - :install:software:snapcraft
    vars:
      SNAP_PACKAGE:
        sh: jq -r '.blueprint.snapPackage' package.json
    log:
      error: Error ensuring `{{.SNAP_PACKAGE}}` is registered
      start: Ensuring `{{.SNAP_PACKAGE}}` is registered
      success: Ensured `{{.SNAP_PACKAGE}}` is registered
    cmds:
      - task: login
      - snapcraft register --yes {{.SNAP_PACKAGE}}
    status:
      - snapcraft list | grep {{.SNAP_PACKAGE}} || [[ "{{OS}}" != "linux" ]]