#!/bin/bash

source /opt/aninix/Uniglot/Bash/header

function ygdl() {
    ### Download a file
    # param path: path to make
    # param newname (optional): output location
    if [ "$newname" != "" ]; then
        wget -O "$newname" "$path";
    else
        wget "$path";
    fi
}

function ygyt() {
    ### Cache from YouTube
    # param path: YouTube URI
    # param newname: output location
    if [ `echo "$path" | grep -c '/watch?v='` -eq 1 ]; then
        path="$(echo "$path" | cut -f 1 -d '&')"
    fi
    if [ "$newname" != "" ]; then
        yt-dlp -o "$newname" "$path";
    else
        yt-dlp "$path";
    fi
}

function ygmp3() {
    uri="$path"
    if [ "$newname" != "" ]; then
        ygmkdir "$newname"
        cd "$newname"
    fi
    if [ `echo "$uri" | grep -c '/watch?v='` -eq 1 ]; then
        uri="$(echo "$uri" | cut -f 1 -d '&')"
    fi
	youtube-mp3 "$uri";
    yggdrasil-set-music-data *.mp3
}

function ygcache() {
    ### Cache files
    # param path: path to move
    # param newname (option): somewhere other than $PWD to move
    # param exec: what to use
    if [ -n "$1" ]; then
        exec="$1"
    fi
    if [ "$newname" != "" ]; then
        $exec "$path" ./"$newname"
    else
        $exec "$path" .
    fi
}

function ygmkdir() {
    ### Make a directory
    # path: directory to make
    if [ -n "$1" ]; then
        path="$1"
    fi
    if [ -d "$path" ]; then
        infoheader "Directory '$path' already existed."
    else
        mkdir -p "$path"
        chmod u+w "$path"
    fi
}

function usage() {
    ### Usage
    # param retcode: what to return
    if [ -z "$1" ]; then
        retcode=0;
    else
        retcode=$1;
    fi
    cat << EOM
AniNIX/Yggdrasil Bash API
Syntax: yggdrasil-get {dl|yt|mp3|cp|mv|mkdir} PATH [new file name in $PWD]
Option:
-- dl:  Use wget
-- yt:  Use yt-dlp
-- mp3: Use youtube-mp3
-- cp:  Copy the file here.
-- mv:  Move the file here.
-- mkdir: Make a folder
EOM
   exit $retcode
}

### Main
export YGGDRASIL="/home/yggdrasil"
if [ "$1" == '-v' ]; then
    set -x
    shift
fi
option="$1"
path="$2"
newname="$3"


if [ "$option" == "" ] || [ "$option" == "-h" ] || [ "$option" == "--help" ] || [ "$path" == "" ]; then
    usage 0;
fi

#Make sure we're in the Yggdrasil project.
if [ $(expr match "$PWD" "$YGGDRASIL") -ne $(expr length "$YGGDRASIL") ]; then
   echo "Not in the Yggdrasil directory.";
   exit;
fi

#unlock this directory
chmod ug+w "$PWD"

if [ $? -ne 0 ]; then
    echo Couldn\'t unlock $PWD
    exit 1
fi

# Functional loop
case "$option" in
    dl) ygdl ;;
    yt) ygyt ;;
    mp3) ygmp3 ;;
    cp) ygcache cp ;;
    mv) ygcache mv ;;
    mkdir) ygmkdir ;;
    *) usage 1 ;;
esac

#Lock
chmod -R ug-w "$PWD"
