#!/bin/zsh

baseDir=~/Temp/Phone
mkdir -p ~/.cache/phone/{screenshots,photos}
mkdir -p $baseDir

is_mounted() {
    mount | awk -v DIR="$1" '{if ($3 == DIR) { exit 0}} ENDFILE{exit -1}'
}

check_mount() {
    if is_mounted $baseDir; then
        echo "Phone is mounted :)"
    else
        echo "Mounting phone..."
        sshfs -o port=2222 -oHostKeyAlgorithms=+ssh-rsa jawz@phone:/ $baseDir
    fi
}

sync_music() {
    check_mount
    echo "Syncing music..."
    rsync --omit-dir-times --size-only --no-perms --recursive --progress \
        --delete $HOME/Music/ $baseDir/Music
}

sync_art() {
    check_mount
    echo "Moving drawings..."
    typeset -A remotes
    remotes=(
        "$HOME/Pictures/Art/My Art/2019/" "$baseDir/Pictures/Art/2019/"
        "$HOME/Pictures/Art/My Art/2020/" "$baseDir/Pictures/Art/2020/"
        "$HOME/Pictures/Art/My Art/2021/" "$baseDir/Pictures/Art/2021/"
        "$HOME/Pictures/Art/4me/" "$baseDir/Pictures/Commissions/"
        "$HOME/Pictures/Art/Artists/Friends/" "$baseDir/Pictures/Friends/"
    )
    for local remote in "${(@kv)remotes}"
    do (
        rsync --omit-dir-times --size-only --no-perms --recursive --progress --delete \
            --exclude={'*.psd','*.clip','*.docx','*.pdf','*.pur','*.ttf','*.zip','*.xcf'} \
            --exclude={'*/Assets','.nomedia','*.sai','*.mp4'} \
            $local $remote
    )
    done
}

sync_photos() {
    check_mount
    echo "Moving photos..."
    mv $baseDir/DCIM/Camera/* $HOME/.cache/phone/photos/
    mv $HOME/.cache/phone/photos/* "$HOME/Pictures/Photos/Camera Roll/"
}

sync_screenshots() {
    check_mount
    echo "Moving screenshots..."
    mv $baseDir/Pictures/Screenshots/* $HOME/.cache/phone/screenshots/
    mv $HOME/.cache/phone/screenshots/* $HOME/Pictures/Screenshots/
}

sync_memes() {
    check_mount
    echo "Moving those memes... lol"
    mv $baseDir/Pictures/Twitter/* "$HOME/Pictures/To Organize/"
    mv $baseDir/Pictures/Reddit/* "$HOME/Pictures/To Organize/"
    mv $baseDir/Pictures/Discord/* "$HOME/Pictures/To Organize/"
}

sync_telegram() {
    check_mount
    echo "Moving telegram media..."
    mv $baseDir/Pictures/Telegram/* "$HOME/Pictures/To Organize/"
}

check_umount() {
    umount $baseDir
    rmdir $baseDir
}

case "$1" in
    mount) check_mount ;;
    music) sync_music ;;
    art) sync_art ;;
    photos) sync_photos ;;
    screenshots) sync_screenshots ;;
    memes) sync_memes ;;
    telegram) sync_telegram ;;
    unmount) unmount ;;
    everything)
        #sync_music
        sync_art
        sync_photos
        sync_screenshots
        sync_memes
        sync_telegram
        check_umount
        ;;
    *)
        echo "not a valid input"
        exit 1
        ;;
esac
