#!/bin/bash

IFS="
"

CORE="/path/to/Pywikibot/core"
SUMMARY="changing link from http->https"
RATE=6
FIX_START=551
FIX_END=650

cd "$CORE"
if [ ! -f "pwb.py" ]; then
   echo "drive_https_upgrade.sh: Can't launch Pywikibot!"
   exit
fi

echo "drive_https_upgrade.sh: Starting at fix $FIX_START..."

FIX_CUR=0
LAST_RUN=0
for THE_LINE in `cat "/path/to/ValExtLinks report.txt"`; do
   if [[ $THE_LINE =~ .*http-\>https.* ]]; then
      let FIX_CUR+=1
      if [ $FIX_CUR -lt $FIX_START ]; then
         continue
      fi
      if [ $FIX_CUR -gt $FIX_END ]; then
         echo "drive_https_upgrade.sh: Stopped after fix $FIX_END."
         exit
      fi

      # Wait for rate limit to expire if we have run the Python script before in this session
      if [ $LAST_RUN -gt 0 ]; then
         CUR_TIME=$(date +%s)
         WAIT_REMAINDER=$(($RATE - $CUR_TIME + $LAST_RUN))
         if [ $WAIT_REMAINDER -gt 0 ]; then
            echo "drive_https_upgrade.sh: Waiting $WAIT_REMAINDER second(s)."
            sleep $WAIT_REMAINDER
         fi
      fi
      ON_PAGE=${THE_LINE#*page \'}
      ON_PAGE=${ON_PAGE%%\'*}
      FROM_LINK=${THE_LINE#*URL \'}
      FROM_LINK=${FROM_LINK%%\'*}
      TO_LINK=${THE_LINE%\'*}
      TO_LINK=${TO_LINK##*\'}
      LAST_RUN=$(date +%s)
      python pwb.py replace -page:"$ON_PAGE" "$FROM_LINK" "$TO_LINK" -summary:"$SUMMARY" -always
   fi
done