#!/usr/bin/env bash

source "$(dirname $0)/vars"

case "$1" in
  domains:get)
    verify_app_name "$2"
    verify_max_args 2 "$@"
    hostnames_for_app "$APP"
	echo "${hostnames[@]}"
	;;

  domains:set)
    verify_app_name "$2"
    shift 2
    echo "$@" > "$DOKKU_ROOT/$APP/HOSTNAME"
    redeploy_app "$APP"
    ;;

  domains:redirect:get)
    verify_app_name "$2"
    verify_max_args 2 "$@"
    hostnames_for_app "$APP"
    echo "${redirect_hostnames[@]}"
    ;;

  domains:redirect:set)
    verify_app_name "$2"
    shift 2
    echo "$@" > "$DOKKU_ROOT/$APP/REDIRECT_HOSTNAME"
    redeploy_app "$APP"
    ;;

  nginx:import-ssl)
    [[ -z $2 ]] && echo "Please specify an app to run the command on" && exit 1
    [[ ! -d "$DOKKU_ROOT/$2" ]] && echo "App $2 does not exist" && exit 1
    [[ -t 0 ]] && echo "Tar archive containing server.crt and server.key expected on stdin" && exit 1
    APP="$2"

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

    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
    domains:get <app>                 Get domains for an app
    domains:set <app> <domains...>    Set app domains
    domains:redirect:get <app>                 Get redirect domains for an app
    domains:redirect:set <app> <domains...>    Set redirect app domains
    nginx:import-ssl <app>                          Imports a tarball from stdin; should contain server.crt and server.key
EOF
    ;;

  *)
    exit $DOKKU_NOT_IMPLEMENTED_EXIT
    ;;
esac
