#!/bin/bash

#
# Copyright 2026 Sergey S. Chernov real.sergeych@gmail.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#

upload_only=false
target=vps   # default: new server; use --old for d.lynglang.com
for arg in "$@"; do
  if [[ "$arg" == "-u" || "$arg" == "--upload-only" ]]; then
    upload_only=true
  elif [[ "$arg" == "--old" ]]; then
    target=com
  fi
done

function checkState() {
  if [[ $? != 0 ]]; then
    echo
    echo -- rsync failed. deploy was not finished. deployed version has not been affected
    echo
    exit 100
  fi
}



# Update docs/idea_plugin.md to point to the latest built IDEA plugin zip
# from ./distributables before building the site. The change is temporary and
# the original file is restored right after the build.
DOC_IDEA_PLUGIN="docs/idea_plugin.md"
DOC_IDEA_PLUGIN_BACKUP="${DOC_IDEA_PLUGIN}.deploy_backup"

function updateIdeaPluginDownloadLink() {
  if [[ ! -f "$DOC_IDEA_PLUGIN" ]]; then
    echo "WARN: $DOC_IDEA_PLUGIN not found; skipping plugin link update"
    return 0
  fi

  # Find the most recently modified plugin zip
  local latest
  latest=$(ls -t distributables/lyng-idea-*.zip 2>/dev/null | head -n 1)
  if [[ -z "$latest" ]]; then
    echo "WARN: no distributables/lyng-idea-*.zip found; leaving $DOC_IDEA_PLUGIN unchanged"
    return 0
  fi

  local base
  base=$(basename "$latest")
  local version
  version="${base#lyng-idea-}"
  version="${version%.zip}"
  local url
  url="https://lynglang.com/distributables/${base}"
  local newline
  newline="### [Download plugin v${version}](${url})"

  # Backup and rewrite the specific markdown line if present
  cp "$DOC_IDEA_PLUGIN" "$DOC_IDEA_PLUGIN_BACKUP" || {
    echo "ERROR: can't backup $DOC_IDEA_PLUGIN"; return 1; }

  # Replace the line that starts with the download header; if not found, append it
  awk -v repl="$newline" 'BEGIN{done=0} \
    /^### \[Download plugin v/ { print repl; done=1; next } \
    { print } \
    END { if (done==0) exit 42 }' "$DOC_IDEA_PLUGIN_BACKUP" > "$DOC_IDEA_PLUGIN"

  local rc=$?
  if [[ $rc -eq 42 ]]; then
    echo "WARN: download link not found in $DOC_IDEA_PLUGIN; appending generated link"
    echo >> "$DOC_IDEA_PLUGIN"
    echo "$newline" >> "$DOC_IDEA_PLUGIN"
  elif [[ $rc -ne 0 ]]; then
    echo "ERROR: failed to update $DOC_IDEA_PLUGIN; restoring original"
    mv -f "$DOC_IDEA_PLUGIN_BACKUP" "$DOC_IDEA_PLUGIN" 2>/dev/null
    return 1
  fi
}

# target settings  (-t com | -t vps)
case "$target" in
  com)
    SSH_HOST=sergeych@d.lynglang.com
    SSH_PORT=22
    ROOT=/bigstore/sergeych_pub/lyng
    ;;
  vps)
    SSH_HOST=sergeych@94.130.36.94
    SSH_PORT=22
    ROOT=/var/www/lynglang
    ;;
  *)
    echo "*** ERROR: unknown target '$target' (use -t com | -t vps)"
    echo "*** stop"
    exit 101
esac

die() { echo "ERROR: $*" 1>&2 ; exit 1; }

function refreshTextmateZip() {
  echo "Refreshing distributables/lyng-textmate.zip from editors/..."
  mkdir -p distributables
  # We use -r for recursive and -q for quiet (optional)
  # -j can be used if we want to junk paths, but the request says "contents of editors/"
  # usually we want to preserve the structure inside editors/
  (cd editors && zip -rq ../distributables/lyng-textmate.zip .)
}


if [[ "$upload_only" == false ]]; then
  # Update the IDEA plugin download link in docs (temporarily), then build, then restore the doc
  refreshTextmateZip
  updateIdeaPluginDownloadLink || echo "WARN: proceeding without updating IDEA plugin download link"

  ./gradlew site:jsBrowserDistribution
  BUILD_RC=$?

  # Always restore original doc if backup exists
  if [[ -f "$DOC_IDEA_PLUGIN_BACKUP" ]]; then
    mv -f "$DOC_IDEA_PLUGIN_BACKUP" "$DOC_IDEA_PLUGIN"
  fi

  if [[ $BUILD_RC -ne 0 ]]; then
    echo
    echo -- build failed. deploy aborted.
    echo
    exit 100
  fi
fi

# Prepare working dir
ssh -p ${SSH_PORT} ${SSH_HOST} "
  cd ${ROOT}
  rm -rd build 2>/dev/null
  if [ -d release ]; then
    echo copying current release
    cp -r release build
  else
    echo creating first release
    mkdir release
    mkdir build
  fi
";

if [[ "$upload_only" == false ]]; then
  # sync files
  SRC=./site/build/dist/js/productionExecutable
  rsync -e "ssh -p ${SSH_PORT}" -avz -r -d --delete ${SRC}/* ${SSH_HOST}:${ROOT}/build/dist
  checkState
  #rsync -e "ssh -p ${SSH_PORT}" -avz  ./static/* ${SSH_HOST}:${ROOT}/build/dist
  #checkState
fi

rsync -e "ssh -p ${SSH_PORT}" -avz -r -d --delete distributables/* ${SSH_HOST}:${ROOT}/build/dist/distributables
checkState

echo
echo finalizing the deploy...
ssh -p ${SSH_PORT} ${SSH_HOST} "
  cd ${ROOT}
  rm -rd release~
  mv release release~
  mv build release
  cd release
  # in this project we needn't restart back when we deploy the front
  #  ~/bin/restart_service
";

if [[ $? != 0 ]]; then
  echo
  echo -- finalization failed. the rease might be corrupt. rolling back is not yet implemented.
  echo
  exit 100
fi

echo
echo Deploy successful
echo

