#!/bin/bash

webhookurl="$1"
baseurl="$2"
currentdir=`pwd`

if [ ! -f '/root/guilded_dir.v3.1.sh' ]
then
    runnerflag="AYAYA! "
    # echo "this script was running on an actions runner"
# else
    # echo "this script was running on a rooted enviernment"
fi

parameters="-H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:125.0) Gecko/20100101 Firefox/125.0' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8' -H 'Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2' -H 'Upgrade-Insecure-Requests: 1' -H 'Sec-Fetch-Dest: document' -H 'Sec-Fetch-Mode: navigate' -H 'Sec-Fetch-Site: same-origin' -H 'Sec-Fetch-User: ?1' -H 'Connection: keep-alive' -H 'Cookie: msite_prod_session=s%3AdfyNB2GAxlNviiRxPeV1DRtOgStQfL3C.dD8%2FN0UVIl5jiVLD%2FSj32757tXitgl0h%2BZXjikvkGaY; mam=65.SA.13.793.5.0.0; mamident=549A1A6D34804C9AB35D073958DE043F.4FE9E486B9D64F09B6637C66FAF61B83; _csrf=Z3fQYWAia9x9eGLIlY-NYiaO; history=%5B%7B%22text%22%3A%22Updates%20Stream%22%2C%22url%22%3A%22%2Fupdates%22%7D%5D; _csrfToken=YsfR9G9y-X9e_8iIBR4XSztU40oznyrcWgs0; auuid=eb6d8820-b20a-4676-bdcb-3051d8d169a8' -H 'If-None-Match: W/"11a2e-ZLRQ2FHtbPnu2o76MyLhehVE+O4"'"

function merge() { # $1 = main file to merge
    for url in `cat "$1" | cut -f1 -d'|'`
    do
        if [ `cat *.txt | grep -F "$url" | grep -c '|1|'` -eq 1 ]
        then
            echo -e "\e[36mpost \e[32m$url\e[36m found guilded link, replacin',,, \e[0m"
            source="$(echo "$url|0" | sed 's:[]\[^$.*/&]:\\&:g')"
            dest="$(cat *.txt | grep -F "$url" | grep '|1|' | sed 's:[]\[^$.*/&]:\\&:g')"
            sed -i "s/$source/$dest/g" "$1"
        fi
    done
}

function merge_v2() { # $1 = main file to merge
    for url in `cat "$1" | grep -E '\|0$' | cut -f1 -d'|'`
    do
        if [ `cat temp/*.txt | grep -F "$url" | grep -c '|1|'` -eq 1 ]
        then
            echo -e "\e[36mpost \e[32m$url\e[36m found guilded link, replacin',,, \e[0m"
            source="$(echo "$url|0" | sed 's:[]\[^$.*/&]:\\&:g')"
            dest="$(cat temp/*.txt | grep -F "$url" | grep '|1|' | sed 's:[]\[^$.*/&]:\\&:g')"
            sed -i "s/$source/$dest/g" "$1"
        else
            echo -e "\e[31mpost \e[32m$url\e[31m didn't find guilded link:bruhfei:\e[0m"
        fi
    done
}

function distribute() { # $1 = main file to merge, $2 = number of threads
    totalposts=0
    threads="$2"
    for url in `cat "$1" | grep -E '\|0$'`
    do
        echo "$url" >> "maindb.part$[$totalposts%$threads+1].txt"
        let totalposts++
    done
}

function migration() {
    cat /dev/null > maindb.txt
    for line in `cat finished list | uniq`
    do
        title="${line##*/}"
        metdate="${line%/*}"
        metdate="${metdate##*/}"
        grepresult=`grep "$title.$metdate" results.txt`
        if [ "$grepresult" ]
        then
            guildedlink=`echo "$grepresult" | cut -f3 -d'|'`
            guildedlinksize=`echo "$grepresult" | cut -f2 -d'|'`
            guildedlinkchecksum=`echo "$grepresult" | cut -f4 -d'|'`
            echo "$line|1|$guildedlink|$guildedlinksize|$guildedlinkchecksum" >> maindb.txt
        else
            echo "$line|0" >> maindb.txt
        fi
    done
}

function sexart_videolist() {
    OLD_IFS=$IFS
    IFS=$'\n'
    
    totalvideos=`eval "curl -k '$baseurl/api/movies?galleryType=MOVIE&first=60&page=1&staffSelectionHead=false&tabId=0&order=DATE&direction=ASC&type=MOVIE' $parameters" | sed 's/,/\n/g' | grep "total" | sed 's/:/\n/g;s/}//g' | grep -Eo [0-9]*`
    
    for page in `seq 1 $((totalvideos/60+1))`
    do
        for line in `eval "curl -k '$baseurl/api/movies?galleryType=MOVIE&first=60&page=$page&staffSelectionHead=false&tabId=0&order=DATE&direction=ASC&type=MOVIE' $parameters" | sed 's/},{/\n/g'`
        do
            if [ `echo $line | grep -c '"isStaffSelection":true'` -eq 0 ] # not staff selection
            then
                selectedurl=`echo $line | sed 's/,/\n/g' | grep path | sed 's/"/\n/g' | grep movie`
                [ "$selectedurl" ] && echo "$selectedurl|0" >> maindb.final.txt
            fi
        done
    done
    
    IFS=$OLD_IFS
}

function sexart_piclist() {
    OLD_IFS=$IFS
    IFS=$'\n'
    
    totalpics=`eval "curl -k '$baseurl/api/galleries?first=60&galleryType=GALLERY&page=1&order=DATE&direction=ASC' $parameters" | sed 's/,/\n/g' | grep "total" | sed 's/:/\n/g;s/}//g' | grep -Eo [0-9]*`
    
    for page in `seq 1 $((totalpics/60+1))`
    do
        for selectedurl in `eval "curl -k '$baseurl/api/galleries?first=60&galleryType=GALLERY&page=$page&order=DATE&direction=ASC' $parameters" | sed 's/},{/\n/g' | sed 's/,/\n/g' | grep path | sed 's/"/\n/g' | grep gallery`
        do
            [ "$selectedurl" ] && echo "$selectedurl|0" >> maindb.final.txt
        done
    done
    IFS=$OLD_IFS
}

# function sexart_pics() { # $1 = title, $2 = date
    # OLD_IFS=$IFS
    # IFS=$'\n'
    # title="$1"
    # metdate="$2"
    # jsontemp=`eval "curl -k --connect-timeout 2 --retry 20 --retry-delay 0 --retry-max-time 40 '$baseurl/api/gallery?name=$title&date=$metdate' $parameters"`
    # echo "$jsontemp"
    # uuid=`echo "$jsontemp" | grep -Po '"originalUUID".*?,' | sed 's/^.*:"//g;s/".*//g'`
    # commentsdump=`eval "curl -k --connect-timeout 2 --retry 20 --retry-delay 0 --retry-max-time 40 '$baseurl/api/comments?objectUUID=$uuid&order=TIMESTAMP&direction=DESC' $parameters"`
    # echo "$commentsdump"
    # for avaliablequality in `echo "$jsontemp" | sed 's/\\\\\\//\\//g;' | grep -Po '"zips":.*' | sed 's/,/\n/g' | grep quality | sed 's/^.*://g;s/"//g'`
    # do
        # eval "curl --connect-timeout 2 --retry 20 --retry-delay 0 --retry-max-time 40 -kI '$baseurl/api/download-media/$uuid/photos/$avaliablequality' $parameters" 2> /dev/null | grep -E "(l|L)ocation:" | sed 's/location: //g;s/Location: //g;s/location://g;s/Location://g' | sed 's/\r//g'
    # done
    # IFS=$OLD_IFS
# }

# function sexart_movie() { # $1 = title, $2 = date
    # OLD_IFS=$IFS
    # IFS=$'\n'
    # title="$1"
    # metdate="$2"
    # jsontemp=`eval "curl --connect-timeout 2 --retry 20 --retry-delay 0 --retry-max-time 40 -k '$baseurl/api/movie?name=$title&date=$metdate' $parameters"`
    # echo "$jsontemp"
    # uuid=`echo "$jsontemp" | grep -Po '"crew":.*?"UUID".*?"name' | sed 's/^.*UUID//g;s/":"//g;s/".*//g'`
    # commentsdump=`eval "curl --connect-timeout 2 --retry 20 --retry-delay 0 --retry-max-time 40 -k '$baseurl/api/comments?objectUUID=$uuid&order=TIMESTAMP&direction=DESC' $parameters"`
    # echo "$commentsdump"
    # for avaliablequality in `echo "$jsontemp" | sed 's/\\\\\\//\\//g;' | grep -Po '"videos":.*?,"zip' | sed 's/"videos":"//g;s/","zip//g' | sed 's/,/\n/g' | grep id | sed 's/^.*://g;s/"//g'`
    # do
        # eval "curl --connect-timeout 2 --retry 20 --retry-delay 0 --retry-max-time 40 -kI '$baseurl/api/download-media/$uuid/film/$avaliablequality' $parameters" 2> /dev/null | grep -E "(l|L)ocation:" | sed 's/location: //g;s/Location: //g;s/location://g;s/Location://g' | sed 's/\r//g'
    # done
    # for avaliablequality in `echo "$jsontemp" | sed 's/\\\\\\//\\//g;' | grep -Po '"zips":.*' | sed 's/,/\n/g' | grep quality | sed 's/^.*://g;s/"//g'` # some sexart movies also contain images zip
    # do
        # eval "curl --connect-timeout 2 --retry 20 --retry-delay 0 --retry-max-time 40 -kI '$baseurl/api/download-media/$uuid/photos/$avaliablequality' $parameters" 2> /dev/null | grep -E "(l|L)ocation:" | sed 's/location: //g;s/Location: //g;s/location://g;s/Location://g' | sed 's/\r//g'
    # done
    # IFS=$OLD_IFS
# }

# function sexart() { # $1 = url
    # url="$1"

    # title="${url##*/}"
    # metdate="${url%/*}"
    # metdate="${metdate##*/}"
    
    # [ `echo "$url" | grep -c "movie"` -gt 0 ] && sexart_movie "$title" "$metdate"
    # [ `echo "$url" | grep -c "gallery"` -gt 0 ] && sexart_pics "$title" "$metdate"
# }

# echo "Content-type: text/plain"
# echo ""

# sexart "$QUERY_STRING"
# exit 0

# sexart "$1"

function antics_pics() { # $1 = title, $2 = date
    OLD_IFS=$IFS
    IFS=$'\n'
    mkdir "$title.$metdate"
    cd "$title.$metdate"
    
    jsontemp=`eval "curl -k --connect-timeout 2 --retry 20 --retry-delay 0 --retry-max-time 40 '$baseurl/api/gallery?name=$title&date=$metdate' $parameters"`
    echo "$jsontemp" > "$title.$metdate.metadata.json"
    uuid=`echo "$jsontemp" | grep -Po '"originalUUID".*?,' | sed 's/^.*:"//g;s/".*//g'`
    commentsdump=`eval "curl -k --connect-timeout 2 --retry 20 --retry-delay 0 --retry-max-time 40 '$baseurl/api/comments?objectUUID=$uuid&order=TIMESTAMP&direction=DESC' $parameters"`
    echo "$commentsdump" > "$title.$metdate.comments.json"
    for avaliablequality in `echo "$jsontemp" | sed 's/\\\\\\//\\//g;' | grep -Po '"zips":.*' | sed 's/,/\n/g' | grep quality | sed 's/^.*://g;s/"//g'` # some sexart movies also contain images zip
    do
        eval "curl --connect-timeout 2 --retry 20 --retry-delay 0 --retry-max-time 40 -kI '$baseurl/api/download-media/$uuid/photos/$avaliablequality' $parameters" 2> /dev/null | grep -E "(l|L)ocation:" | sed 's/location: //g;s/Location: //g;s/location://g;s/Location://g' | sed 's/\r//g'
    done >> list
    IFS=$OLD_IFS
    
    aria2c --check-certificate=false -k 1M -x 64 -s 64 -j 64 -R -c --auto-file-renaming=false -i list
    
    cd ..
}

function antics_movie() { # $1 = title, $2 = date
    OLD_IFS=$IFS
    IFS=$'\n'
    mkdir "$title.$metdate"
    cd "$title.$metdate"
    
    jsontemp=`eval "curl --connect-timeout 2 --retry 20 --retry-delay 0 --retry-max-time 40 -k '$baseurl/api/movie?name=$title&date=$metdate' $parameters"`
    echo "$jsontemp" > "$title.$metdate.metadata.json"
    uuid=`echo "$jsontemp" | grep -Po '"crew":.*?"UUID".*?"name' | sed 's/^.*UUID//g;s/":"//g;s/".*//g'`
    commentsdump=`eval "curl --connect-timeout 2 --retry 20 --retry-delay 0 --retry-max-time 40 -k '$baseurl/api/comments?objectUUID=$uuid&order=TIMESTAMP&direction=DESC' $parameters"`
    echo "$commentsdump" > "$title.$metdate.comments.json"
    for avaliablequality in `echo "$jsontemp" | sed 's/\\\\\\//\\//g;' | grep -Po '"videos":.*?,"zip' | sed 's/"videos":"//g;s/","zip//g' | sed 's/,/\n/g' | grep id | sed 's/^.*://g;s/"//g'`
    do
        eval "curl --connect-timeout 2 --retry 20 --retry-delay 0 --retry-max-time 40 -kI '$baseurl/api/download-media/$uuid/film/$avaliablequality' $parameters" 2> /dev/null | grep -E "(l|L)ocation:" | sed 's/location: //g;s/Location: //g;s/location://g;s/Location://g' | sed 's/\r//g'
    done >> list
    for avaliablequality in `echo "$jsontemp" | sed 's/\\\\\\//\\//g;' | grep -Po '"zips":.*' | sed 's/,/\n/g' | grep quality | sed 's/^.*://g;s/"//g'` # some sexart movies also contain images zip
    do
        eval "curl --connect-timeout 2 --retry 20 --retry-delay 0 --retry-max-time 40 -kI '$baseurl/api/download-media/$uuid/photos/$avaliablequality' $parameters" 2> /dev/null | grep -E "(l|L)ocation:" | sed 's/location: //g;s/Location: //g;s/location://g;s/Location://g' | sed 's/\r//g'
    done >> list
    IFS=$OLD_IFS
    
    aria2c --check-certificate=false -k 1M -x 64 -s 64 -j 64 -R -c --auto-file-renaming=false -i list
    
    cd ..
}

# function downloadantics() {
    # OLD_IFS=$IFS
    # IFS=$'\n'

    # totallines=`cat list | wc -l`
    # currentlines=0

    # while [ -f "list" ]
    # do
        # currentline=`head -1 list`
        # title="${currentline##*/}"
        # metdate="${currentline%/*}"
        # metdate="${metdate##*/}"
        
        # [ `echo "$url" | grep -c "movie"` -gt 0 ] && antics_movie >> log 2>&1
        # [ `echo "$url" | grep -c "gallery"` -gt 0 ] && antics_pics >> log 2>&1
        # time "$currentdir"/gd31.sh "$title.$metdate" "$webhookurl" >> log 2>&1
        # rm "$title.$metdate" -rf
            
        # head -1 list >> finished
        # tail -n +2 list > list2
        # [ -s "list2" ] && mv list2 list
        # mkdir currentprogress
        # cp -p list finished currentprogress/
        # mv log currentprogress/
        # time "$currentdir"/gd32.sh "currentprogress" "k-kawaii navia chan ist mein blue eyes waifu! " "$webhookurl" > /dev/null 2> /dev/null
        # rm currentprogress -rf
        
        # let currentlines++
        # echo -e "\e[32m$title.$metdate\e[36m finished in \e[32m`date`, \e[36m$currentlines\e[32m/$totallines\e[0m"
    # done

    # IFS=$OLD_IFS
# }

function bruhfei() {
    [ `echo "$url" | grep -c "movie"` -gt 0 ] && time antics_movie 
    [ `echo "$url" | grep -c "gallery"` -gt 0 ] && time antics_pics
    [ "$runnerflag" ] && time "$currentdir"/gd31.sh "$title.$metdate" "$webhookurl" || time ~/guilded_dir.v3.1.sh "$title.$metdate" "$webhookurl"
}

function bruhfei114514() {
    time bruhfei
}

function downloadantics_v2() {
    OLD_IFS=$IFS
    IFS=$'\n'

    for line in `cat maindb.txt`
    do
        url=`echo "$line" | cut -f1 -d'|'`
        if [ `echo "$line" | cut -f2 -d'|'` -eq 0 ]
        then
            echo -e "\e[36mprocessin' \e[32m$url\e[0m"
            title="${url##*/}"
            metdate="${url%/*}"
            metdate="${metdate##*/}"

            time bruhfei114514 >> log 2>&1
            rm "$title.$metdate" -rf
            
            guildedlink=`grep "$postid" results.txt | tail -1 | cut -f3 -d'|'`
            guildedlinksize=`grep "$postid" results.txt | tail -1 | cut -f2 -d'|'`
            guildedlinkchecksum=`grep "$postid" results.txt | tail -1 | cut -f4 -d'|'`
            
            echo -e "\e[36mpost \e[32m$url\e[36m finished processin', change written into maindb\e[0m"
            
            source="$(echo "$url|0" | sed 's:[]\[^$.*/&]:\\&:g')"
            dest="$(echo "$url|1|$guildedlink|$guildedlinksize|$guildedlinkchecksum" | sed 's:[]\[^$.*/&]:\\&:g')"
            sed -i "s/$source/$dest/g" maindb.txt
            
            if [ "$runnerflag" ]
            then
                mkdir currentprogress
                cp -p maindb.txt results.txt currentprogress/
                mv log currentprogress/
                time "$currentdir"/gd32.sh "currentprogress" "k-kawaii navia chan ist mein blue eyes waifu! " "$webhookurl" > /dev/null 2> /dev/null
                rm currentprogress -rf
            fi
        else
            echo -e "\e[31m$url was either processed, or didn't need to process\e[0m"
        fi
    done

    IFS=$OLD_IFS
}

downloadantics_v2
