#!/bin/zsh

set -e
set -x

usage() {
    print "Usage: ${0:t} [-r repo_url] [-d dest_dir] [-h]"
    print ""
    print "  -r repo_url  Mercurial repo URL to clone."
    print "               Default: ssh://pnyc@dabel.us.oracle.com//workspace/pnyc/solaris-reviews/on-sru"
    print "  -d dest_dir  Local directory to clone into."
    print "               Default: ~/PycharmProjects/<repo_name>"
    print "  -h           Show this help text."
    print ""
    print "The script exits if dest_dir already exists."
}

ensure_clone_identity_loaded() {
    local ssh_host="$1"
    local identity_file=""
    local identity_pub=""

    ssh_host="${ssh_host%%:*}"

    identity_file=$(ssh -G "$ssh_host" 2>/dev/null | awk '/^identityfile / {print $2; exit}')
    if [[ -z "$identity_file" ]]; then
        return 0
    fi

    identity_file=${~identity_file}
    identity_pub="${identity_file}.pub"

    if [[ ! -f "$identity_file" || ! -f "$identity_pub" ]]; then
        return 0
    fi

    if ssh-add -T "$identity_pub" >/dev/null 2>&1; then
        return 0
    fi

    print "Loading SSH identity for ${ssh_host}: ${identity_file}"
    ssh-add --apple-use-keychain "$identity_file" >/dev/null 2>&1 || ssh-add "$identity_file"
}

DEFAULT_PARENT_WS='ssh://pnyc@dabel.us.oracle.com//workspace/pnyc/solaris-reviews/on-sru'
# Example repo URLs:
# ssh://pnyc@andel.us.oracle.com//workspace/pnyc/solaris-reviews/secure-integrate/userland11.4
# ssh://pnyc@andel.us.oracle.com//workspace/pnyc/solaris-reviews/userland-pipeline
# ssh://pnyc@andel.us.oracle.com//workspace/pnyc/solaris-reviews/akidr-text
# ssh://pnyc@andel.us.oracle.com//workspace/pnyc/solaris-reviews/akidr
PARENT_WS="$DEFAULT_PARENT_WS"
DEST_DIR=''

while getopts ":r:d:h" opt; do
    case "$opt" in
        r)
            PARENT_WS="$OPTARG"
            ;;
        d)
            DEST_DIR="$OPTARG"
            ;;
        h)
            usage
            exit 0
            ;;
        :)
            print -u2 "Missing argument for -$OPTARG"
            usage >&2
            exit 1
            ;;
        \?)
            print -u2 "Unknown option: -$OPTARG"
            usage >&2
            exit 1
            ;;
    esac
done

shift $((OPTIND - 1))

if [[ $# -ne 0 ]]; then
    print -u2 "Unexpected positional arguments: $*"
    usage >&2
    exit 1
fi

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

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

if [[ -z "$DEST_DIR" ]]; then
    DEST_DIR=~/PycharmProjects/${REPO}
fi

DEST_DIR=${~DEST_DIR}
DEST_DIR=${DEST_DIR:A}

if [[ -e "$DEST_DIR" ]]; then
    print -u2 "Destination already exists: $DEST_DIR"
    exit 1
fi

HG_CLONE_ARGS=()
if [[ "$PARENT_WS" == ssh://* ]]; then
    SSH_CLONE_HOST=${${PARENT_WS#ssh://}%%/*}
    SSH_CLONE_HOST=${SSH_CLONE_HOST#*@}
    ensure_clone_identity_loaded "$SSH_CLONE_HOST"

    # Avoid exhausting ssh-agent identities before ssh reaches the host-specific
    # IdentityFile from ~/.ssh/config (for example ~/.ssh/dabel.key).
    HG_CLONE_ARGS+=(--config "ui.ssh=ssh -o BatchMode=yes -o IdentitiesOnly=yes")
fi

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

# /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
mkdir -p "${DEST_DIR:h}"
hg "${HG_CLONE_ARGS[@]}" clone "$PARENT_WS" "$DEST_DIR"
pwd
cd "$DEST_DIR"
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 "$DEST_DIR/common/etc"
$CP passwd.template passwd

# set up dev defaults
cd "$DEST_DIR/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

if [[ -d "$DEST_DIR/solaris/on/production" ]]; then
    LINT_DIR="$DEST_DIR/solaris/on/production"
elif [[ -d "$DEST_DIR/solaris/userland/sru" ]]; then
    LINT_DIR="$DEST_DIR/solaris/userland/sru"
else
    print -u2 "Unable to determine lint directory under $DEST_DIR/solaris"
    exit 1
fi

source proxy off
cd "$LINT_DIR"
make FAKE_DEVEL_ENV=yes lint
