#!/bin/bash

set -eu

source ./utils/common.sh

WORKDIR=/home/oscarzhou/source/github.com/portainer
GLOBAL_VOLUME=/home/oscarzhou/volumes
TRUE=0;
FALSE=1;
REPO_DIR=
REPO_VOLUME=

function debug_portainer_client() {
    print_highlight "[debug portainer client]"
    yarn
    yarn start:client
}

function generate_portainer_jwt_token() {
    print_highlight "[generate portainer jwt token]"
        
    read -p "Username(admin):" username
    if [ -z "$username" ]; then 
        username="admin";
    fi 

    read -p "Password(****):" password
    read -p "Address(http://127.0.0.1:9000):" address
    if [ -z "$address" ]; then 
        address="http://127.0.0.1:9000";
    fi 

    payload="{\"username\":\"${username}\",\"password\":\"${password}\"}"
    curl -d ${payload} -H 'Content-Type: application/json' "${address}/api/auth"
}

function list_portainer_ee_menu() {
    print_highlight "Your current working directory is ${WORKDIR}/portainer-ee"
    if ! prompt_continue; then 
        exit;
    fi 

    REPO_DIR=${WORKDIR}/portainer-ee
    print_highlight "Your current volume is ${VOLUME}/portainer-ee-data"
    if ! prompt_continue; then
        exit;
    fi

    REPO_VOLUME=${VOLUME}/portainer-ee-data

    PS3='Please select the action: '
    OPTIONS=(
        'Debug Client'
        'Lint Client'
        'Run Unit Test for Client'
        'Before Commit'
        'Build Client'
        'Build Server'
        'Run Unit Test for Server'
        'Get Portainer CE API Reference'
        'Quit'
    )

    select opt in "${OPTIONS[@]}"
    do
        case $opt in 
            'Debug Client')
                debug_portainer_client
                ;;
            'PortainerCE')
                build_portainer_frontend
                ;;
            'Build Portainer EE/CE Backend')
                build_portainer_backend
                ;;
            'Generate Portainer EE/CE JWT')
                generate_portainer_jwt
                ;;
            'Run Before Commit [Portainer EE/CE]')
                run_before_commit
                ;;
            'Get Portainer CE API Reference')
                get_portainer_ce_api_reference
                ;;
            'Quit')
                break
                ;;
        esac
    done
}

function code_security_scan_summary() {
    echo "
        1. Scan client with snyk: $(print_highlight "snyk test")
        2. Scan server with snyk: $(print_highlight "cd api && snyk test")
        3. If snyk is not authenticated: $(print_highlight "snyk auth")
        4. Specify the severity threshold: $(print_highlight "snyk test --severity-threshold=<low|medium|high|critical>")
        5. Other commands with snyk: $(print_highlight "snyk --help")
    "

    echo "
        Steps to scan portainer image with Trivy:
        1. Build the local image: $(print_highlight "docker build -t oscarzhou/portainer:dev-ee -f build/linux/Dockfile .")
        2. Scan with trivy: $(print_highlight 'docker run --rm -v "/var/run/docker.sock":"/var/run/docker.sock" aquasec/trivy:latest image oscarzhou/portainer:dev-ee')
        3. Other commands with trivy: $(print_highlight 'docker run --rm -v "/var/run/docker.sock":"/var/run/docker.sock" aquasec/trivy:latest --help')
    "
}

function look_up_curl_commands() {
    input "1.POST 2.GET 3.PUT 4.DELETE :" option
    if [[ "${option}" == "1" ]]; then 
        echo "$(print_highlight "curl -d '{\"repository\":\"https://github.com/portainer/portainer-ee\",\"username\":\"oscarzhou\", \"password\":\"your PAT\"}' -H 'Content-Type: application/json' -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsInJvbGUiOjEsInNjb3BlIjoiZGVmYXVsdCIsImZvcmNlQ2hhbmdlUGFzc3dvcmQiOmZhbHNlLCJleHAiOjE2NjAwMzQ2MjUsImlhdCI6MTY2MDAwNTgyNX0.S0UbPO4POD9kbuWOmvO9WR6LY6v424bpGw46rlEkNs0' http://127.0.0.1:9000/api/gitops/repo/refs")"
    elif [[ "${option}" == "2" ]]; then 
        echo "$(print_highlight "curl -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsInJvbGUiOjEsInNjb3BlIjoiZGVmYXVsdCIsImZvcmNlQ2hhbmdlUGFzc3dvcmQiOmZhbHNlLCJleHAiOjE2NTUxMTg2ODUsImlhdCI6MTY1NTA4OTg4NX0.mJSZomeiEpRlz36MxSsLFWpUbA0BHRXWYijsZAo1NWc' http://127.0.0.1:9000/api/users/1/gitcredentials")"
    elif [[ "${option}" == "3" ]]; then 
        echo "$(print_highlight "curl -X PUT http://127.0.0.1:9000/api/users/1/gitcredentials/11 -d '{"name":"test-credential-11","username":"cred11", "password":"cred11"}' -H 'Content-Type: application/json' -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsInJvbGUiOjEsInNjb3BlIjoiZGVmYXVsdCIsImZvcmNlQ2hhbmdlUGFzc3dvcmQiOmZhbHNlLCJleHAiOjE2NTcwODQ5MzUsImlhdCI6MTY1NzA1NjEzNX0.kUhkhhSt4WH33Q3hYzLwsYDv1a9a2ygCi6p8MkKMbwc'")"
    elif [[ "${option}" == "4" ]]; then 
        echo "$(print_highlight "curl -X DELETE http://192.168.1.109:9000/api/users/1/gitcredentials/1 -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsInJvbGUiOjEsInNjb3BlIjoiZGVmYXVsdCIsImZvcmNlQ2hhbmdlUGFzc3dvcmQiOmZhbHNlLCJleHAiOjE2NTQ3NTc1NzYsImlhdCI6MTY1NDcyODc3Nn0.GlxGmL6XTTH29Ns8aRnX5qp1qBfDVF2zaPzuSmG7qUs'")"
    else
        print_error "Invalid option"
    fi
}


function menu() {
    PS3='Please select the action/repository: '
    OPTIONS=(
        'PortainerEE'
        'PortainerCE'
        'Build Portainer EE/CE Backend'
        'Generate Portainer JWT Token'
        'Run Before Commit [Portainer EE/CE]'
        'Get Portainer CE API Reference'
        'Look Up Curl Commands'
        'Code Security Scan'
        'Cleanup Temporary Volume'
        'Quit'
    )

    select opt in "${OPTIONS[@]}"
    do
        case $opt in 
            'PortainerEE')
                list_portainer_ee_menu
                ;;
            'PortainerCE')
                build_portainer_frontend
                ;;
            'Build Portainer EE/CE Backend')
                build_portainer_backend
                ;;
            'Generate Portainer JWT Token')
                generate_portainer_jwt
                ;;
            'Run Before Commit [Portainer EE/CE]')
                run_before_commit
                ;;
            'Get Portainer CE API Reference')
                get_portainer_ce_api_reference
                ;;
            'Look Up Curl Commands')
                look_up_curl_commands
                ;;
            'Code Security Scan')
                code_security_scan_summary
                ;;
            'Cleanup Temporary Volume')
                cleanup_temporary_volume 
                ;;
            'Quit')
                break
                ;;
        esac
    done
}

# check if the function exists (bash specific)
if [ "$#" -eq 0 ]; then
  menu
else 
  "$@"
fi
