#!/bin/bash
#
# Copyright (C) 2019-Present A-Team Digital Solutions
#

# Upload -- AndroidFileHost
upload_afh() {
  cp -r $FINAL_ROM_LOCATION/$DEVICE_NAME/$ROM_NAME $FINAL_ROM_LOCATION/AFH-Uploads
  export DOWNLOAD_LINK="https://androidfilehost.com/?w=files&flid=341764"
  lftp -e "mirror -R $FINAL_ROM_LOCATION/AFH-Uploads /Roms; bye" $AFH_LOGIN
  rm -rf $FINAL_ROM_LOCATION/AFH-Uploads
}


# Upload -- Forgejo
upload_fgj() {
  # === CONFIG ===
  FILE_PATH="${FINAL_ROM_LOCATION}/${UPLOAD_DEVICE_NAME}/${UPLOAD_ROM_NAME}"
  RELEASE_NAME="${UPLOAD_ROM_NAME}"
  export DOWNLOAD_LINK="https://ateam.gotadell.com/${USER_NAME}/${UPLOAD_DEVICE_NAME}/releases/download/${TAG}/${UPLOAD_ROM_NAME}"

  # === VALIDATE ===
  if [[ -z $UPLOAD_ROM_NAME || -z $FINAL_ROM_LOCATION || -z $USER_NAME || -z $API_TOKEN ]]; then
    echo "[!] Missing One Or More Required Environment Variables."
    return 1
  fi

  echo "[*] Uploading Rom: $UPLOAD_ROM_NAME..."
  echo "[*] File Path: $FILE_PATH"

  if [[ ! -f "$FILE_PATH" ]]; then
    echo "[!] File Not Found At: $FILE_PATH"
    return 1
  fi

  # === CREATE RELEASE ===
  echo "[*] Creating Release (if it doesn't already exist)..."
  CREATE_RESPONSE=$(curl -s -w "%{http_code}" -o /tmp/release_response.json -X POST "${FORGEJO_URL}/api/v1/repos/${USER_NAME}/${UPLOAD_DEVICE_NAME}/releases" \
    -H "Authorization: token ${API_TOKEN}" \
    -H "Content-Type: application/json" \
    -d '{
          "tag_name": "'"$TAG"'",
          "target_commitish": "'"$BRANCH"'",
          "name": "'"$RELEASE_NAME"'",
          "body": "* Automated Upload Via A-Team Build Menu",
          "draft": false,
          "prerelease": false
        }')

  HTTP_CODE=$(tail -n1 <<< "$CREATE_RESPONSE")
  if [[ "$HTTP_CODE" != "201" && "$HTTP_CODE" != "409" ]]; then
    echo "[!] Failed To Create Or Get Release. HTTP $HTTP_CODE"
    cat /tmp/release_response.json
    return 1
  fi

  # === GET RELEASE ID ===
  RELEASE_ID=$(jq -r '.id' /tmp/release_response.json)
  if [[ -z "$RELEASE_ID" || "$RELEASE_ID" == "null" ]]; then
    echo "[!] Failed To Get Release ID."
    cat /tmp/release_response.json
    return 1
  fi

  echo "[*] Release ID: $RELEASE_ID"

  # === UPLOAD FILE ===
  echo "[*] Uploading File To Release..."
  UPLOAD_RESPONSE=$(curl --progress-bar --show-error --write-out "%{http_code}" --output /tmp/upload_response.json \
    -X POST "${FORGEJO_URL}/api/v1/repos/${USER_NAME}/${UPLOAD_DEVICE_NAME}/releases/${RELEASE_ID}/assets?name=${UPLOAD_ROM_NAME}" \
    -H "Authorization: token ${API_TOKEN}" \
    -H "Content-Type: application/octet-stream" \
    --upload-file "$FILE_PATH")

  HTTP_UPLOAD_CODE="$UPLOAD_RESPONSE"

  if [[ "$HTTP_UPLOAD_CODE" == "201" ]]; then
    echo "[✓] Successfully Uploaded $UPLOAD_ROM_NAME"
    echo "[→] Download: $DOWNLOAD_LINK"
  else
    echo "[!] Upload Failed. HTTP $HTTP_UPLOAD_CODE"
    cat /tmp/upload_response.json
  fi

  # === GENERATE & UPLOAD CHECKSUM ===
  if [[ "$GENERATE_CHECKSUM" == true ]]; then
    echo "[*] Generating ${CHECKSUM_TYPE^^} Checksum..."

    case "$CHECKSUM_TYPE" in
      md5)    SUM_CMD="md5sum" ;;
      sha1)   SUM_CMD="sha1sum" ;;
      sha256) SUM_CMD="sha256sum" ;;
      sha512) SUM_CMD="sha512sum" ;;
      *)      echo "[!] Unsupported checksum type: $CHECKSUM_TYPE"; return 1 ;;
    esac

    CHECKSUM_FILE="${FILE_PATH}.${CHECKSUM_TYPE}"
    $SUM_CMD "$FILE_PATH" > "$CHECKSUM_FILE"

    echo "[*] Uploading Checksum File: $(basename "$CHECKSUM_FILE")..."

    CSUM_HTTP=$(curl --progress-bar --show-error --write-out "%{http_code}" --output /tmp/checksum_upload_response.json \
      -X POST "${FORGEJO_URL}/api/v1/repos/${USER_NAME}/${UPLOAD_DEVICE_NAME}/releases/${RELEASE_ID}/assets?name=$(basename "$CHECKSUM_FILE")" \
      -H "Authorization: token ${API_TOKEN}" \
      -H "Content-Type: text/plain" \
      --upload-file "$CHECKSUM_FILE")

    if [[ "$CSUM_HTTP" == "201" ]]; then
      echo "[✓] Checksum Uploaded Successfully"
    else
      echo "[!] Checksum Upload Failed. HTTP $CSUM_HTTP"
      cat /tmp/checksum_upload_response.json
    fi
  fi

  #curl --progress-bar -X POST "${FORGEJO_URL}/api/v1/repos/${USER_NAME}/${UPLOAD_DEVICE_NAME}/releases/${RELEASE_ID}/assets?name=${UPLOAD_ROM_NAME}" \
  #  -H "Authorization: token ${API_TOKEN}" \
  #  -H "Content-Type: application/octet-stream" \
  #  --upload-file "$FILE_PATH" \
  #  --write-out "\n[✓] Upload Complete: %{http_code}\n"

  #echo "$UPLOAD_RESPONSE"

  #if echo "$UPLOAD_RESPONSE" | grep -q "→ Upload HTTP: 20"; then
  #  echo "[✓] Successfully Uploaded $UPLOAD_ROM_NAME"
  #  echo "[→] Download: $DOWNLOAD_LINK"
  #else
  #  echo "[!] Upload Failed. Inspect Output Above."
  #fi
}


# Upload -- SourceForge
upload_sfg() {
  export DOWNLOAD_LINK="https://sourceforge.net/projects/a-team-rom-downloads/files/$UPLOAD_DEVICE_NAME/$UPLOAD_ROM_NAME"
  expect - <<_END_EXPECT
  set timeout 360 ;  # set timeout to 6 minutes for the password prompt
  spawn scp $FINAL_ROM_LOCATION/$DEVICE_NAME/$ROM_NAME $SFG_USER@frs.sourceforge.net:/home/frs/project/a-team-rom-downloads/$DEVICE_NAME
  expect {
      "assword:" {
          send "$SFG_PASS\r"
          set timeout -1 ;  # remove timeout for rest of process
          exp_continue
      }
      timeout {
          puts "Timeout Occurred While Waiting For Password Prompt."
          exit 1
      }
      eof {
          puts "End Of File Reached."
      }
  }
_END_EXPECT
}


# Upload -- File Select
upload_file_selector() {
  if [[ -z $FINAL_ROM_LOCATION || -z $SFG_USER || -z $SFG_PASS ]]; then
    echo "Error: Missing Required Parameters"
    return 1
  fi

  # List Device Folders
  echo ""
  echo "Available Device Folders:"
  select DEVICE_NAME in $(ls -d ${FINAL_ROM_LOCATION}/*/ 2>/dev/null | xargs -n 1 basename); do
    if [[ -n $DEVICE_NAME ]]; then
      break
    else
      echo ""
      echo "Invalid Selection. Please Try Again"
    fi
  done

  # List Files In The Selected Device Folder
  echo ""
  echo ""
  echo "Available Files In $DEVICE_NAME:"
  select ROM_NAME in $(ls ${FINAL_ROM_LOCATION}/${DEVICE_NAME}/*.zip 2>/dev/null | xargs -n 1 basename); do
    if [[ -n $ROM_NAME ]]; then
      clear
      export UPLOAD_ROM_NAME=$ROM_NAME  # Export the selected $ROM_NAME
      break
    else
      echo ""
      echo "Invalid Selection. Please Try Again"
    fi
  done

  echo ""

}


upload_sanity() {
    if [[ $? -eq 0 ]]; then
        echo -e "\n\nUpload Successful\n"
        chmod +x Telegram_Bots/Telegram_Bot-$DEVICE_NAME.sh
        if [[ $TARGET_IS_GSI == true ]]; then
        chmod +x Telegram_Bots/Bot_Message_GSI.sh
        ./Telegram_Bots/Bot_Message_GSI.sh
        else            
        chmod +x Telegram_Bots/Bot_Message.sh
        ./Telegram_Bots/Bot_Message.sh
        echo -e "\n"
        fi
    else
        echo -e "\n\nUpload Failed"
        echo "Better Luck Next Time"
        echo "Please Try Again!"
        echo -e "\nPRESS ENTER TO RELOAD"
        read
        # Remove Unneeded Changelog.txt
        cd ../../../../
        rm -rf Changelog.txt
        exec "$BASH" "$0" "$@"
    fi
}


upload_service_selector() {
    while true; do
        case $UPLOAD in
            AFH)
                clear
                echo -e "\nUploading To Android File Host (AFH)...\n"
                upload_afh
                break  # Exit the loop after successful upload
                ;;
            FGJ)
                clear
                echo -e "\nUploading To ForgeJo (FGJ)...\n"
                upload_fgj
                break  # Exit the loop after successful upload
                ;;
            SFG)
                clear
                echo -e "\nUploading To SourceForge (SFG)...\n"
                upload_sfg
                break  # Exit the loop after successful upload
                ;;
            *)
                clear
                echo ""
                echo "Unknown Upload Service Selected. Please Choose Again"; sleep 5; clear; menu_upload_service;
                ;;
        esac
    done
}
