#!/bin/bash

TYPE=new

while getopts t: flag
do
    case "${flag}" in
        t) TYPE=${OPTARG};;
    esac
done

if [ $TYPE != 'new' ]  && [ $TYPE != 'update' ]; then
    echo "Error: -t can only take values as new or update"
    echo "you passed -t as $TYPE"
    exit 0
fi

command -v ansible >/dev/null 2>&1 || { echo >&2 "Error: Ansible not installed. Please install it and try again. Aborting."; exit 1; }
command -v ansible-playbook >/dev/null 2>&1 || { echo >&2 "Error: ansible-playbook not installed. Please install it and try again. Aborting."; exit 1; }
command -v docker >/dev/null 2>&1 || { echo >&2 "Error: Docker not installed. Please install it and try again. Aborting."; exit 1; }

# Check for Docker Compose (supports both v2 plugin and legacy standalone)
if docker compose version >/dev/null 2>&1; then
    DOCKER_COMPOSE="docker compose"
elif command -v docker-compose >/dev/null 2>&1; then
    DOCKER_COMPOSE="docker-compose"
else
    echo >&2 "Error: Docker Compose not installed. Please install it and try again."
    echo >&2 "  For Docker Compose v2: It comes bundled with Docker Desktop"
    echo >&2 "  For legacy docker-compose: Install from https://docs.docker.com/compose/install/"
    exit 1
fi

command -v npm >/dev/null 2>&1 || { echo >&2 "Error: npm not installed. Please install it and try again. Aborting."; exit 1; }
command -v pnpm >/dev/null 2>&1 || { echo >&2 "Error: pnpm not installed. Please install it and try again. Aborting."; exit 1; }
command -v node >/dev/null 2>&1 || { echo >&2 "Error: node not installed. Please install it and try again. Aborting."; exit 1; }
command -v aws >/dev/null 2>&1 || { echo >&2 "Error: aws-cli not installed. Please install it and try again. Aborting."; exit 1; }

if ! docker info > /dev/null 2>&1; then
    echo "Error: This script uses docker, and it isn't running - please start docker and try again!"
    exit 1
fi

api_image=$(docker images -q 103233932089.dkr.ecr.us-east-1.amazonaws.com/dev-api:debian)
orchard_image=$(docker images -q 103233932089.dkr.ecr.us-east-1.amazonaws.com/dev-orchard:latest)
workstation_image=$(docker images -q 103233932089.dkr.ecr.us-east-1.amazonaws.com/dev-workstation:latest)

if [ -z "${api_image}" ] || [ -z "${orchard_image}" ] || [ -z "${workstation_image}" ]
then
    [ -n "${api_image}" ] || echo "Error: Please pull dev-api:debian image from dev aws ecr"
    [ -n "${orchard_image}" ] || echo "Error: Please pull dev-orchard:latest image from dev aws ecr"
    [ -n "${workstation_image}" ] || echo "Error: Please pull dev-workstation:latest image from dev aws ecr"
    echo "Please generate aws temp creds for dev aws account and pull the above mentioned images."
    exit 1
fi

DIRECTORY_PATH="$(dirname "$(pwd)")"
BASE_PATH="$(dirname "$DIRECTORY_PATH")"
HOME_DIR="$(basename "$DIRECTORY_PATH")"
GITHUB_SSH=git@github.com:theorchard
GITHUB_HTTP=https://github.com/theorchard

# sync's the users forked branch by rebasing it with orchard master branch
# parameters $1 = `github remote url` $2 = `directory name` $3 = `remote upstream name`
syncForkedBranch(){
    cd ${DIRECTORY_PATH}/$2
    git remote add $3 $1
    git fetch $3
    git rebase $3/master
    git push origin master
    cd ${DIRECTORY_PATH}
}

if [ $TYPE == 'new' ]; then
    read -p "Are you sure you want to continue? This will remove the orchard, workstation, api and forntend-workstation clone if already exists in ${DIRECTORY_PATH}.(y/n)" new 
    new=${new:-N}
    if [ $new == 'y' ] || [ $new == 'Y' ]; then
        sudo rm -rf ${DIRECTORY_PATH}/{orchard,api,workstation,frontend-workstation}
        
        free_space=`df -k . | awk -F ' ' '{print $4}' | tail -n1`
        (( $(echo "$free_space > 3670016" | bc -l) )) || { echo "Error: Your system is low on space. start.sh alteast needs 3.5gb to run smoothly."; exit 1; }

        mkdir -p ${DIRECTORY_PATH}/{orchard,api,workstation,frontend-workstation}

        echo -n "Enter your github username:"
        read username
        echo -n "Enter your upstream name:"
        read upstreamname
        echo -n "Have you set github ssh public key? (y/n)"
        read setcreds

        if [ $setcreds == 'y' ]; then
            git clone git@github.com:${username}/orchard.git ${DIRECTORY_PATH}/orchard
            syncForkedBranch ${GITHUB_SSH}/orchard.git orchard ${upstreamname}

            git clone git@github.com:${username}/api.git ${DIRECTORY_PATH}/api
            syncForkedBranch ${GITHUB_SSH}/api.git api ${upstreamname}

            git clone git@github.com:${username}/workstation.git ${DIRECTORY_PATH}/workstation
            syncForkedBranch ${GITHUB_SSH}/workstation.git workstation ${upstreamname}

            git clone git@github.com:${username}/frontend-workstation.git ${DIRECTORY_PATH}/frontend-workstation
            syncForkedBranch ${GITHUB_SSH}/frontend-workstation.git frontend-workstation ${upstreamname}
        else
            echo -n "Enter your personal git token:"
            read -s token

            git clone https://${username}:${token}@github.com/${username}/orchard.git ${DIRECTORY_PATH}/orchard
            syncForkedBranch ${GITHUB_HTTP}/orchard.git orchard ${upstreamname}

            git clone https://${username}:${token}@github.com/${username}/api.git ${DIRECTORY_PATH}/api
            syncForkedBranch ${GITHUB_HTTP}/api.git api ${upstreamname}

            git clone https://${username}:${token}@github.com/${username}/workstation.git ${DIRECTORY_PATH}/workstation
            syncForkedBranch ${GITHUB_HTTP}/workstation.git workstation ${upstreamname}

            git clone https://${username}:${token}@github.com/${username}/frontend-workstation.git ${DIRECTORY_PATH}/frontend-workstation
            syncForkedBranch ${GITHUB_HTTP}/frontend-workstation.git frontend-workstation ${upstreamname}
        fi
    fi
fi

if [ ! "$(ls -A ${DIRECTORY_PATH}/orchard)" ] || [ ! "$(ls -A ${DIRECTORY_PATH}/api)" ] || [ ! "$(ls -A ${DIRECTORY_PATH}/workstation)" ] || [ ! "$(ls -A ${DIRECTORY_PATH}/frontend-workstation)" ]; then
    [ ! "$(ls -A ${DIRECTORY_PATH}/orchard)" ] && echo "Error: Orchard cloning failed, orchard folder is empty in ${DIRECTORY_PATH}"
    [ ! "$(ls -A ${DIRECTORY_PATH}/workstation)" ] && echo "Error: Workstation cloning failed, workstation folder is empty in ${DIRECTORY_PATH}"
    [ ! "$(ls -A ${DIRECTORY_PATH}/api)" ] && echo "Error: Api cloning failed, api folder is empty in ${DIRECTORY_PATH}"
    [ ! "$(ls -A ${DIRECTORY_PATH}/frontend-workstation)" ] && echo "Error: frontend-workstation cloning failed, frontend-workstation folder is empty in ${DIRECTORY_PATH}"
    exit 0
fi

CONFIG_FILE=${DIRECTORY_PATH}/ansible-dev-box-setup/config/configs.yml
if [ ! -f "$CONFIG_FILE" ]; then
    echo "Error: ${CONFIG_FILE} file cannot be found"
    echo "First copy the configs.shadow.yml file into configs.yml file available in ${DIRECTORY_PATH}/ansible-dev-box-setup/config folder"
    echo "And update the configs.yml file."
    exit 0
fi

cp ${DIRECTORY_PATH}/ansible-dev-box-setup/dev ${DIRECTORY_PATH}/ansible-dev-box-setup/ansible/hosts/dev

basepath=(`echo $(perl -ne "/DEVORCH_BASE_PATH:/ && print" ${DIRECTORY_PATH}/ansible-dev-box-setup/config/configs.yml) | tr ':' ' '`)
if [ ${#basepath[@]} == '1' ] ; then
    perl -i -pe "s+DEVORCH_BASE_PATH:+DEVORCH_BASE_PATH: ${BASE_PATH}+;" ${DIRECTORY_PATH}/ansible-dev-box-setup/config/configs.yml
fi

homedir=(`echo $(perl -ne "/DEVORCH_HOME_DIR:/ && print" ${DIRECTORY_PATH}/ansible-dev-box-setup/config/configs.yml) | tr ':' ' '`)
if [ ${#homedir[@]} == '1' ] ; then
    perl -i -pe "s+DEVORCH_HOME_DIR:+DEVORCH_HOME_DIR: ${HOME_DIR}+;" ${DIRECTORY_PATH}/ansible-dev-box-setup/config/configs.yml
fi

sysuser=(`echo $(perl -ne "/SYSTEM_USERNAME:/p && print" ${DIRECTORY_PATH}/ansible-dev-box-setup/config/configs.yml) | tr ':' ' '`)
if [ ${#sysuser[@]} == '1' ] ; then
    perl -i -pe "s+SYSTEM_USERNAME:+SYSTEM_USERNAME: ${USER}+;" ${DIRECTORY_PATH}/ansible-dev-box-setup/config/configs.yml
fi

ansible-playbook -i ${DIRECTORY_PATH}/ansible-dev-box-setup/ansible/hosts/dev ${DIRECTORY_PATH}/ansible-dev-box-setup/ansible/devorch.yml --extra-var "SETUP_ENV='local'"

DOCKER_COMPOSE_FILE=${DIRECTORY_PATH}/docker-compose.yml
if [ -f "$DOCKER_COMPOSE_FILE" ]; then
    echo "Ansible script successfully ran"
    
    cd ${DIRECTORY_PATH}

    # pull proxy image if does not exists already
    [ -n "\$(/usr/bin/docker images -q haproxytech/haproxy-alpine:2.4)" ] || { echo "Pulling haproxy image"; ${DOCKER_COMPOSE} pull proxy; }

    # pull memcache image if does not exists already
    [ -n "\$(/usr/bin/docker images -q memcached:latest)" ] || { echo "Pulling memcache image"; ${DOCKER_COMPOSE} pull memcache; }

    # pull redis image if does not exists already
    [ -n "\$(/usr/bin/docker images -q bitnami/redis:latest)" ] || { echo "Pulling redis image"; ${DOCKER_COMPOSE} pull redis; }

    # pull haproxytech image if does not exists already
    [ -n "\$(/usr/bin/docker images -q httpd:latest)" ] || { echo "Pulling httpd image"; ${DOCKER_COMPOSE} pull frontend; }

    ${DOCKER_COMPOSE} up -d

    # check if all the container has started properly if not then retry docker compose up
    [[ `${DOCKER_COMPOSE} ps | grep "Exit" | wc -l` == 0 ]] || ${DOCKER_COMPOSE} up -d
    [[ `${DOCKER_COMPOSE} ps | grep "Exit" | wc -l` == 0 ]] || { echo "Error: while ${DOCKER_COMPOSE} up, your setup is located at ${DIRECTORY_PATH}"; echo "Manually go to the above path and try ${DOCKER_COMPOSE} up and check error."; exit 1; }

    serverhost=(`echo $(perl -ne "/DEVORCH_SERVER_HOSTNAME:/p && print" ${DIRECTORY_PATH}/ansible-dev-box-setup/config/configs.yml) | tr ':' ' '`)

    servername=(`echo $(perl -ne "/DEVORCH_SERVER:/p && print" ${DIRECTORY_PATH}/ansible-dev-box-setup/config/configs.yml) | tr ':' ' '`)

    oa_url=https://oa.127.0.0.1.nip.io
    alw_url=https://alw.127.0.0.1.nip.io
    vapi_url=https://vapi.127.0.0.1.nip.io

    echo "Success: Setup's can be found at ${DIRECTORY_PATH}."
    echo "and your urls are as follows:"
    echo "OA URL: $oa_url"
    echo "ALW URL: $alw_url"
    echo "VAPI URL: $vapi_url"
else
    echo "Error: Ansible playbook failed"
fi  
