#!/bin/sh

# TODO: support config locations:
# ./.piku-server
# ~/.piku-server
# git config --get remote.piku.url
# git config --get remote.paas.url

if grep -q WSL /proc/version 2>/dev/null
then
  # On WSL, use the Windows ssh.exe to benefit from 1Password integration
  SSH="ssh.exe"
else
  SSH="ssh"
fi

remote_name="piku"
if [ "$1" = "--remote" ] || [ "$1" = "-r" ]
then
  shift
  remote_name="$1"
  shift
fi

gitremote=$(git config --get remote."$remote_name".url)
remote=${gitremote:-"${PIKU_SERVER}:${PIKU_APP}"}

githome="https://raw.githubusercontent.com/piku/piku/master/"

out() { printf "%s\n" "$*" >&2; }

if [ "$1" = "init" ]
then
  if [ -f "ENV" ]
  then
    echo "ENV file already exists."
  else
    curl -s "${githome}examples/ENV" > ENV && echo "Wrote ./ENV file."
  fi
  if [ -f "Procfile" ]
  then
    echo "Procfile already exists."
  else
    curl -s "${githome}examples/Procfile" > Procfile && echo "Wrote ./Procfile."
  fi
  if [ "$gitremote" = "" ]
  then
    echo "Now set up your piku remote for this app:"
    echo "git remote add piku piku@HOSTNAME:APPNAME"
  fi
  exit
fi

out "Piku remote operator."

if [ "$remote" = "" ] || [ "$remote" = ":" ]
then
  out
  out "Error: no piku server configured."
  out "Use PIKU_SERVER=piku@MYSERVER.NET or configure a git remote called 'piku'."
  out
else
  server=$(echo "$remote" | cut -f1 -d":" 2>/dev/null)
  app=$(echo "$remote" | cut -f2 -d":" 2>/dev/null)
  # gather SSH flags
  while [ "${1#\-}"x != "${1}x" ];
  do
    sshflags="${sshflags} ${1}"
    shift
  done
  # check the Piku command to be run
  cmd="$1"
  out "Server: $server"
  out "App: $app"
  out
  case "$cmd" in
    ""|help)
      command $SSH -o LogLevel=QUIET ${sshflags:+${sshflags}} "$server" "$@" | grep -v "INTERNAL"
      echo "  shell             Local command to start an SSH session in the remote."
      echo "  init              Local command to download an example ENV and Procfile."
      echo "  download          Local command to scp down a remote file. args: REMOTE-FILE(s) LOCAL-PATH"
      echo "                    Remote file path is relative to the app folder."
      ;;
    apps|setup|setup:ssh|update)
      # shellcheck disable=SC2029 # caused by the final "$@", expanded on the client side
      command $SSH ${sshflags:+${sshflags}} "$server" "$@"
      ;;
    shell)
      $SSH -t "$server" run "$app" bash
      ;;
    download)
      scp "$server:~/.piku/apps/${app}/${2}" "${3:-'.'}"
      ;;
    *)
      shift # remove cmd arg
      # shellcheck disable=SC2029 # caused by the final "$@", expanded on the client side
      command $SSH ${sshflags:+${sshflags}} "$server" "$cmd" "$app" "$@"
      ;;
  esac
fi
