#!/bin/bash

LINK="$1"
date=$(date '+%H%M%S%d%m%Y')
DLDIR="Downloads/TikTok"

if [ ! -d $HOME/$DLDIR ]; then
    if [ -d $HOME/Unduhan ]; then
        DLDIR="Unduhan/TikTok"
    fi
    if [ -d /sdcard/Download ]; then
        ln -s /sdcard/Download $HOME/Downloads
        mkdir -p $HOME/$DLDIR/Pictures
        mkdir -p $HOME/$DLDIR/Videos
    else
        mkdir -p $HOME/$DLDIR/Pictures
        mkdir -p $HOME/$DLDIR/Videos
    fi
fi

start_download() {
    user=$(echo $href | cut -d '/' -f4)
    echo "Username: $user"
    uid=$(echo $href | cut -d '/' -f6 | cut -d '?' -f 1)
    echo "User ID: $uid"
    format=$(echo $href | cut -d '/' -f5)
    echo "Format: $format"
    name=$(echo $user | cut -d '@' -f2)
    if [ ${format} == "video" ]; then
        if [ ! -d $HOME/$DLDIR/Videos/${name} ]; then
            mkdir -p $HOME/$DLDIR/Videos/${name}
        fi
        aria2c -d $HOME/$DLDIR/Videos/${name} -m 0 -x 10 -c https://tikwm.com/video/media/hdplay/${uid}.mp4 -o ${user}_${uid}.mp4
    fi
    if [ ${format} == "photo" ]; then
        for x in `curl -sk 'https://tikwm.com/api/?url='${uid}'&count=12&cursor=0&web=1&hd=1' | tr '"' '\n' | grep https | grep -i '.jpeg' | tr -d '\\\\'`
        do
            let cnt++
            if [ ! -d $HOME/$DLDIR/Pictures/${name} ]; then
                mkdir -p $HOME/$DLDIR/Pictures/${name}
            fi
            wget -q -c ${x} -O $HOME/$DLDIR/Pictures/${name}/${user}_${uid}_${cnt}.jpeg
        done
        unset x
        echo -e "Total: ${cnt} photo"
    fi
    return 0
}

tiktok_android()
{
    echo -e "Retrieve user information ...\n"
    getlink=$(curl -sk $LINK | grep https |  tr -d '<"')
    fixlink=$(echo $getlink | cut -d ';' -f 1 | cut -d '&' -f 1)
    export $fixlink
    unset a
    start_download
}

tiktok_web()
{
    echo -e "Retrieve user information ...\n"
    href=$LINK
    start_download
}

more_download()
{
    read -p "Link: " LINK;
    if [[ $LINK == 'https://vt.tiktok.com/'* ]]; then
        tiktok_android
    elif [[ $LINK == 'https://www.tiktok.com/'* ]]; then
        tiktok_web
    fi
    $0 -m
}

case $1 in
    https://vt.tiktok.com/*)
        tiktok_android
        ;;
    https://www.tiktok.com/*)
        tiktok_web
        ;;
    https://vm.tiktok.com/*)
        echo -e "Sorry, does not support tiktok lite url"
        exit
        ;;
    -m|--more)
        more_download
        ;;
    -v|--version)
        echo "1.2.0-SR"
        ;;
    -h|--help|*)
        echo -e "Usage: tiktok-download [URL] [options]\n\nOptions:\n  -m, --more                    download more video\n  -h, --help                    show help screen"
        ;;
esac

