#!/bin/zsh

set -e
set -x

# function to get PARENT_WS as a parameter
# default value is 'ssh://pnyc@andel.us.oracle.com//workspace/pnyc/solaris-reviews/secure-integrate/userland11.4'
#

if [[ -z $1 ]]; then
    # PARENT_WS='ssh://pnyc@andel.us.oracle.com//workspace/pnyc/solaris-reviews/secure-integrate/userland11.4'
    # PARENT_WS='ssh://pnyc@andel.us.oracle.com//workspace/pnyc/solaris-reviews/userland-pipeline'
    # PARENT_WS='ssh://pnyc@andel.us.oracle.com//workspace/pnyc/solaris-reviews/akidr-text'
    PARENT_WS='ssh://pnyc@andel.us.oracle.com//workspace/pnyc/solaris-reviews/akidr'
else
    PARENT_WS=$1
fi

# remove trailing slash
PARENT_WS="${PARENT_WS%/}"

JENKINS_CLONE_FROM="ssh://${PARENT_WS##ssh://pnyc@}"
FOLDER_PREFIX='PetrN/'
POINT_OF_CONTACT='petr.nyc@oracle.com'
SLACK_CHANNEL='@pnyc'
DIR=$(pwd)

REPO=${PARENT_WS##*/}                      # userland11.4

# /workspace/pnyc/solaris-reviews/secure-integrate/userland11.4
SCRIPT_DIR_BASE=$(echo "$PARENT_WS" | awk '{sub(/^.*\/\//,"/"); print}')
MV=/bin/mv
RM=/bin/rm
CP=/bin/cp
CAT=/bin/cat

pwd
hg clone "$PARENT_WS"
pwd
cd "${DIR}/${REPO}"
pwd

source proxy off
$RM -rf venv

# this holds upgraded python-jenkins - will it work?
sed -E 's/^git.*$/git+file:\/\/\/Users\/jetpac\/PycharmProjects\/python-jenkins/' requirements.txt > /tmp/r
mv /tmp/r requirements.txt

common/tools/create_virtualenv /opt/homebrew/bin/python3.11 requirements.txt venv

echo '[alias]'                  >> .hg/hgrc
echo 'ci = ci -X Makefile.inc'  >> .hg/hgrc
echo 'st = st -X Makefile.inc'  >> .hg/hgrc

tmpmake=$(mktemp)
sed 's:PYTHON3=python3.7:PYTHON3=python3.11:g' < Makefile.inc > "$tmpmake"
$MV "$tmpmake" Makefile.inc


# set up pwd
cd "${DIR}/${REPO}/common/etc"
$CP passwd.template passwd

# set up dev defaults
cd "${DIR}/${REPO}/common/jobs/"
cp defaults.devel.tmpl defaults.devel.yml
cp defaults.stage.tmpl defaults.stage.yml

$CAT > defaults_devel_patch <<- CATT
9c9
<       script_dir_base: "/workspace/pzahradn/jenkins/mrspatmore"
---
>       script_dir_base: "${SCRIPT_DIR_BASE=}"
11a12
>       pipeline_workspace: "${JENKINS_CLONE_FROM}"
14c15
<       folder_prefix: "pez-"              # Could be used to deploy the devel jobs to different jenkins folder
---
>       folder_prefix: "${FOLDER_PREFIX}"              # Could be used to deploy the devel jobs to different jenkins folder
16c17
<       point_of_contact: "petr.zahradnik@oracle.com"
---
>       point_of_contact: "${POINT_OF_CONTACT}"
21c22
<       slack_channel: "@pzahradn"
---
>       slack_channel: "${SLACK_CHANNEL}"
CATT



patch -p0 defaults.devel.yml < defaults_devel_patch

source proxy off
cd "${DIR}/${REPO}/solaris/userland/sru/"
make lint
