#!/bin/bash

RED=$(tput setaf 1)
NC=$(tput sgr0)       # reset / no color
CYAN=$(tput setaf 6)
LOG_FILE=$(find "$HOME" -maxdepth 1 -name ".mgmtlogin-*" -mmin -840 2>/dev/null | head -1)
if [[ -z "$LOG_FILE" ]]; then
  echo "${RED}Attention!${NC}You are not logged in to Pagely. Please login"
  pagely-auth -e mwcs -s
fi
read -p "What do you need to do? 
Check failed change domain job (1)
Check failed sync job (2)
Check disk space usage (3)
Verify domain for MSSL (4)
Connect via SSH (5)
Check if domain is added on another app (6)
Exit (0)
" ANSWER
case "$ANSWER" in
  [0])
    echo "Exiting."
    exit 0
  ;;
  [1])
    echo "Continuing..."
    read -p "App ID: " PARAM
    OUTPUT=$(script -q -c "pagely-mgmt -e mwcs status:list-jobs-for-app "$PARAM" --format=table" /dev/null)
    echo "pagely-mgmt -e mwcs status:list-jobs-for-app "$PARAM" --format=table"
    printf '%s\n' "$OUTPUT"
    JOB=$(echo "$OUTPUT" | grep -i "modify-domains" | head -n 1)
    if [ -z "$JOB" ]; then
      echo "${RED}Attention!${NC} No modify-domains job ID found. Aborting."
      exit 1
    fi
    ID=$(echo "$JOB" | awk '{print $2}')
    STATUS=$(echo "$JOB" | awk '{print $6}')
    TIME=$(echo "$JOB" | awk '{print $16}')
    echo "${CYAN}Found job with ID${NC} "$ID" ${CYAN}and status${NC} "$STATUS" ${CYAN}started at${NC} "$TIME""
    if [[ "$STATUS" == "SUCCESS" ]]; then
      echo "${CYAN}Job already completed successfully.${NC}"
      exit 1
    fi
    if [[ "$STATUS" == "RUNNING" ]]; then
      echo "${CYAN}Job is still running. Nothing to do.${NC}"
      exit 1
    fi
    OUTPUT=$(script -q -c  "pagely-mgmt -e mwcs workflows:sfn:execution:list --statusJobId "$ID" | jq '.data[] | .sfnResults.execution'" /dev/null)
    echo "pagely-mgmt -e mwcs workflows:sfn:execution:list --statusJobId "$ID" | jq '.data[] | .sfnResults.execution"
    echo "$OUTPUT"
    if echo "$OUTPUT" | grep -iq 'cause.*Failed to modify domains'; then 
      DOMAIN=$(echo "$OUTPUT" | grep '"cause"' | sed 's/\x1b\[[0-9;]*m//g' | tr -d '\r' | grep -o '\\"[^\\]*\\":\\"[^\\]*\\"' | awk -F'\\\\\"' '{print $2}' | head -n 1)
      echo "${CYAN}Let's check if the domain is on another app.${NC}"
      echo "pagely-plat-search -e v2-prod "$DOMAIN""
      pagely-plat-search -e v2-prod "$DOMAIN"
      echo "${CYAN}Also checking the domain with www${NC}"
      echo "pagely-plat-search -e v2-prod www."$DOMAIN""
      pagely-plat-search -e v2-prod www."$DOMAIN"
    fi
    if echo "$OUTPUT" | grep -iq 'redriveStatus.*NOT_REDRIVABLE'; then
      echo "${RED}Attention!${NC} This item is NOT redrivable. Aborting."
      exit 1
    fi
    read -p "Has the underlying issue been fixed and the job can be re-driven? (y/n): " ANSWER
    case "$ANSWER" in
      [Yy])
        echo "Continuing..."
        echo "pagely-mgmt -e mwcs workflows:sfn:execution:redrive:bulk  --run "$ID""
        pagely-mgmt -e mwcs workflows:sfn:execution:redrive:bulk  --run "$ID"
        echo "${CYAN}Waiting 5 seconds before checking the new job.${NC}"
        sleep 5
        OUTPUT=$(script -q -c "pagely-mgmt -e mwcs status:list-jobs-for-app "$PARAM" --format=table" /dev/null)
        echo "pagely-mgmt -e mwcs status:list-jobs-for-app "$PARAM" --format=table"
        printf '%s\n' "$OUTPUT"
      ;;
      [Nn])
        echo "Aborted."
        exit 0
      ;;
      *)
        echo "Invalid input. Aborting."
        exit 1
      ;;
    esac
  ;;
  [2])
    echo "Continuing..."
    read -p "App ID: " PARAM
    OUTPUT=$(script -q -c "pagely-mgmt -e mwcs status:list-jobs-for-app "$PARAM"  --format=table" /dev/null)
    echo "pagely-mgmt -e mwcs status:list-jobs-for-app "$PARAM"  --format=table"
    printf '%s\n' "$OUTPUT"
    JOB=$(echo "$OUTPUT" | grep -i "app-clone" | head -n 1)
    if [ -z "$JOB" ]; then
      echo "${RED}Attention!${NC} No app-clone job ID found. Aborting."
      exit 1
    fi
    ID=$(echo "$JOB" | awk '{print $2}')
    STATUS=$(echo "$JOB" | awk '{print $6}')
    echo "${CYAN}Found job with ID${NC} "$ID" ${CYAN}and status${NC} "$STATUS""
    if [[ "$STATUS" == "PENDING" ]]; then
      echo "${CYAN}Job is currently pending. Nothing to do.${NC}"
      exit 1
    fi
    if [[ "$STATUS" == "RUNNING" ]]; then
      echo "${CYAN}Job is still running. Nothing to do.${NC}"
      exit 1
    fi
    if [[ "$STATUS" == "SUCCESS" ]]; then
      echo "${CYAN}Job already completed successfully.${NC}"
      exit 1
    fi
    echo "pagely-mgmt -e mwcs status:get-job-status "$ID" | jq . | grep -i -C3 error;"
    pagely-mgmt -e mwcs status:get-job-status "$ID" | jq . | grep -i -C3 error;
    read -p "Has the error been checked and should the app clone job be set to SUCCESS? (y/n): " ANSWER
    case "$ANSWER" in
      [Yy])
        echo "Continuing..."
        echo "pagely-mgmt -e mwcs status:update-job-status "$ID" pre-check NA; pagely-mgmt -e mwcs status:update-job-status "$ID" file-sync NA; pagely-mgmt -e mwcs status:update-job-status "$ID" db-sync NA; pagely-mgmt -e mwcs status:update-job-status "$ID" search-replace NA; pagely-mgmt -e mwcs status:update-job-status "$ID" post-install NA; pagely-mgmt -e mwcs status:update-job-status "$ID" copy-static-files SUCCESS"
        pagely-mgmt -e mwcs status:update-job-status "$ID" pre-check NA; pagely-mgmt -e mwcs status:update-job-status "$ID" file-sync NA; pagely-mgmt -e mwcs status:update-job-status "$ID" db-sync NA; pagely-mgmt -e mwcs status:update-job-status "$ID" search-replace NA; pagely-mgmt -e mwcs status:update-job-status "$ID" post-install NA; pagely-mgmt -e mwcs status:update-job-status "$ID" copy-static-files SUCCESS
        echo "${CYAN}Checking if the job was set to SUCCESS.${NC}"
        OUTPUT=$(script -q -c "pagely-mgmt -e mwcs status:list-jobs-for-app "$PARAM" --format=table" /dev/null)
        echo "pagely-mgmt -e mwcs status:list-jobs-for-app "$PARAM" --format=table"
        printf '%s\n' "$OUTPUT"
      ;;
      [Nn])
        echo "Aborted."
        exit 0
      ;;
      *)
        echo "Invalid input. Aborting."
        exit 1
      ;;
    esac
  ;;
  [3])
    echo "Continuing..."
    read -p "Entitlement ID: " PARAM
    echo "pagely-mgmt -e mwcs apps:resource-usage:summary --entitlementId "$PARAM""
    pagely-mgmt -e mwcs apps:resource-usage:summary --entitlementId "$PARAM"
    read -p "Have you checked the disk space and need to upate it? (y/n): " ANSWER
    case "$ANSWER" in
      [Yy])
        echo "Continuing..."
        echo "pagely-mgmt -e mwcs apps:resource-usage:request-update --entitlementId "$PARAM""
        pagely-mgmt -e mwcs apps:resource-usage:request-update --entitlementId "$PARAM"
      ;;
      [Nn])
        echo "Aborted."
        exit 0
      ;;
      *)
        echo "Invalid input. Aborting."
        exit 1
      ;;
    esac
  ;;
  [4])
    echo "Continuing..."
    read -p "Domain name : " PARAM1
    read -p "Unique ID : " PARAM2
    echo "pagely-mgmt -e v2-prod ssl:pki:create-validation-token "$PARAM1" godaddy "$PARAM2" GODADDY_HTML_VALIDATION"
    pagely-mgmt -e v2-prod ssl:pki:create-validation-token "$PARAM1" godaddy "$PARAM2" GODADDY_HTML_VALIDATION
  ;;
  [5])
    echo "Continuing..."
    read -p "App ID: " PARAM
    echo "pagely-connect -e mwcs -s app-"$PARAM""
    pagely-connect -e mwcs -s app-"$PARAM"
  ;;
  [6])
    echo "Continuing..."
    read -p "Domain name: " PARAM
    echo "pagely-plat-search -e v2-prod "$PARAM""
    pagely-plat-search -e v2-prod "$PARAM"
    echo "${CYAN}Also checking the domain with www${NC}"
    echo "pagely-plat-search -e v2-prod www."$PARAM""
    pagely-plat-search -e v2-prod www."$PARAM"
  ;;
  *)
    echo "Invalid input. Please choose a valid option."
  ;;
esac