#!/usr/bin/env bash
set -eo pipefail; [[ $DOKKU_TRACE ]] && set -x

case "$1" in
  nginx:import-ssl)
    if [[ -z $2 ]]; then
      echo "Please specify an app to create"
      exit 1
    fi
    APP="$2"
    if [[ ! -d "$DOKKU_ROOT/$APP" ]]; then
      echo "App $APP does not exist"
      exit 1
    fi
    if [[ -t 0 ]]; then
      echo "Tar archive containing server.crt and server.key expected on stdin"
      exit 1
    fi

    TEMP_DIR=`mktemp -d`
    cd $TEMP_DIR
    tar xvf - <&0
    if [[ -f "$TEMP_DIR/server.crt" ]]; then
      echo "Tar archive missing server.crt"
      exit 1
    fi
    if [[ -f "$TEMP_DIR/server.key" ]]; then
      echo "Tar archive missing server.key"
      exit 1
    fi

    mkdir -p "$DOKKU_ROOT/$APP/tls"
    mv "$TEMP_DIR/server.crt" "$DOKKU_ROOT/$APP/tls/server.crt"
    mv "$TEMP_DIR/server.key" "$DOKKU_ROOT/$APP/tls/server.key"
    rm -rf $TEMP_DIR
    ;;
  help | nginx:help)
    cat  && cat<<EOF
    nginx:import-ssl <app>                          Imports a tarball from stdin; should contain server.crt and server.key
EOF
    ;;

esac
