#!/bin/bash
# Updates the driving tarball with a fresh clone so the merge queue has a
# more up-to-date copy to work with.
arg_1="$1"
if [[ "$arg_1" == "" ]]; then
  arg_1="-t"
fi

# from desktops, /mnt/sun-tcs01/infra/tools is owned by it:it
#    uid=1000(it) gid=1000(it)
#    uid=1160775266(zoox) gid=1160774145(domain^users)
#
# from pipedream, zoox:zoox
#    'it' doesn't exist
#    uid=1000(zoox) gid=1000(zoox)
#
# so, use the number instead of the name

tcs_id="1000"
tcs_group="1000"

if [[ "$(grep -c :${tcs_id}: /etc/passwd)" != "1" ]]; then
  echo "Incorrect user ID for sun-tcs01/infra/tools/merge_queue permissions"
  exit 1
fi

if [[ "$(grep -c :${tcs_group}: /etc/group)" != "1" ]]; then
  echo "Incorrect group ID for sun-tcs01/infra/tools/merge_queue permissions"
  exit 1
fi

if [[ "${arg_1/[tdb]/}" != "-" || "$arg_1" == "-" ]]; then
  echo "Invalid argument: '$arg_1'"
  echo "=========================="
  echo "usage: $0 [-t|-d|-b]"
  echo " "
  echo "where: -t only build and deploy the tarballs (default)"
  echo "       -d only create the directories and refresh the links to the tarballs"
  echo "       -b do both"
  exit 1
fi

mount_point="/mnt/sun-tcs01/infra/tools/merge_queue/merge_queue_dirs"

set -euo pipefail

if [[ "$arg_1" == "-t" || "$arg_1" == "-b" ]]; then
  for owner in ci-testing zooxco; do
    destination_dir="${mount_point}/${owner}_prod_merge_queue"
    # parent directories may not be owned by the executing process
    sudo mkdir -p "$destination_dir"
    remote="git@git.zooxlabs.com:${owner}/driving.git"
    destination_file="$destination_dir/driving.tar.gz"
    # an existing target directory may not be owned by the executing process
    temp_file=$(sudo mktemp --tmpdir="$destination_dir" --suffix=_driving.tar.gz)
    # Make scratch space to clone the repo.
    cd "$(mktemp --directory)"
    # Start by extracting the existing tarball if it exists.
    if [[ -f "$destination_file" ]]; then
      mkdir driving
      cd driving
      tar --extract --gzip --file "$destination_file"
    else
      git clone "$remote"
      cd driving
    fi
    # Make sure that everything is up to date.
    git fetch --prune
    git checkout master
    git reset --hard origin/master
    # Clean up the repo a bit before creating the tarball.
    git remote prune origin
    git gc
    sudo tar --create --gzip --file "$temp_file" ./
    sudo mv "$temp_file" "$destination_file"
    sudo chown "$tcs_id":"$tcs_group" "$destination_file"
    sudo chmod a+r "$destination_file"
  done
fi

#
# now generate all the different tcs directories needed
# to host and link to the two different tarballs
#
owner_list='ci-testing zooxco'
prefix_list='planner_ vehicle_ lite_ demo_ ""'
env_list='dev test prod'
suffix_list='_planner _qa_test _master ""'
repo_name_list='driving calibration'

function setup_directory {
  echo mkdir -p "$1"
  echo ln -sf "${2}_prod_merge_queue/driving.tar.gz" "${1}"
  echo touch "${1}/log"
  echo touch "${1}/state.json"
  echo touch "${1}/state_staging.json"
}

if [[ "$arg_1" == "-d" || "$arg_1" == "-b" ]]; then
  for owner in $owner_list; do
    for repo_name in $repo_name_list; do
      for prefix in $prefix_list; do
        for env in $env_list; do
          dirname="${mount_point}/${owner}_${repo_name}_${env}_${prefix}merge_queue"
          if [[ "$prefix" == '""' ]]; then
            for suffix in $suffix_list; do
              setup_directory "${dirname}${suffix}" "${mount_point}/${owner}"
            done
          else
            setup_directory "${dirname}" "${mount_point}/${owner}"
          fi
        done
      done
    done
  done | sudo bash
  # make sure IT:IT owns everything under $mount_point
  sudo chown -R "$tcs_id":"$tcs_group" "$mount_point"
  # make sure that everything is read/write/execute by the owner and read/searchable directories for world
  sudo chmod -R u+rwx,go+rX "$mount_point"
  # however, the log files for the merge queues are often appended to by non-owner processes
  find "$mount_point" -name "*log*" -exec sudo chmod a+w {} \;
  # as well as the state files used by the merge queues
  find "$mount_point" -name "*state*json*" -exec sudo chmod a+w {} \;
  # Create symbolic links from those most used MQs in production for easy access
  root_folder="/mnt/sun-tcs01/infra/tools/merge_queue"
  ln -s "${mount_point}/zooxco_driving_prod_merge_queue" "${root_folder}/merge_queue"
  sudo chown -R "$tcs_id":"$tcs_group" "${root_folder}/merge_queue"
  ln -s "${mount_point}/zooxco_driving_prod_lite_merge_queue" "${root_folder}/lite_merge_queue_driving"
  sudo chown -R "$tcs_id":"$tcs_group" "${root_folder}/lite_merge_queue_driving"
  ln -s "${mount_point}/zooxco_calibration_prod_lite_merge_queue" "${root_folder}/lite_merge_queue_calibration"
  sudo chown -R "$tcs_id":"$tcs_group" "${root_folder}/lite_merge_queue_calibration"
  ln -s "${mount_point}/zooxco_driving_prod_vehicle_merge_queue" "${root_folder}/vehicle_merge_queue"
  sudo chown -R "$tcs_id":"$tcs_group" "${root_folder}/vehicle_merge_queue"
  ln -s "${mount_point}/zooxco_driving_prod_planner_merge_queue" "${root_folder}/planner_merge_queue"
  sudo chown -R "$tcs_id":"$tcs_group" "${root_folder}/planner_merge_queue"
  ln -s "${mount_point}/zooxco_driving_prod_merge_queue_planner" "${root_folder}/merge_queue_planner"
  sudo chown -R "$tcs_id":"$tcs_group" "${root_folder}/merge_queue_planner"
  ln -s "${mount_point}/zooxco_driving_prod_merge_queue_qa_test" "${root_folder}/merge_queue_qa_test"
  sudo chown -R "$tcs_id":"$tcs_group" "${root_folder}/merge_queue_qa_test"
fi
