#!/usr/bin/env bash
cReset="[0m"
cBold="[1m"
colorBlack=0
colorRed=1
colorGreen=2
colorYellow=3
colorBlue=4
colorMagenta=5
colorCyan=6
colorWhite=7
colorDefault=9
cGreen="[0;3${colorGreen}m"${cBold}
cRed="[1;3${colorRed}m"${cBold}
cYellow="[1;3${colorYellow}m"${cBold}
cBlue="[1;3${colorBlue}m"${cBold}
cMagenta="[1;3${colorMagenta}m"${cBold}

function sync_install_py(
    return
    echo -ne "${cReset}Syncing ${cMagenta}install.py${cReset} to ${cBlue}common.py${cReset} ..."
    cd pyradio
    # Extract values from common.py
    SESSION_LOCKED_VALUE=$(grep "'session-locked'" common.py | sed -E "s/.*'session-locked': '([^']*)'.*/\1/")
    WIN_TITLE_VALUE=$(grep "'win-title'" common.py | sed -E "s/.*'win-title': '([^']*)'.*/\1/")

    # Update values in install.py
    sed -i "s/\('session-locked': '\)[^']*\(.*\)/\1$SESSION_LOCKED_VALUE\2/" install.py
    sed -i "s/\('win-title': '\)[^']*\(.*\)/\1$WIN_TITLE_VALUE\2/" install.py
    cd ..
    git add pyradio/install.py
    echo -e "${cGreen} done${sReset}
"
)

function update_brew_link(){
    local INSERT
    local MACOS_FILE
    echo -e "Working on ${cBlue}docs/macos.md${cReset}"
    echo -n '  Updating brew link ... '
    INSERT=$(curl -s https://brew.sh/ | grep '<figure class="highlight"><pre>' | sed '2,$d' | sed 's/<[^>]*>//g')

    # Check if INSERT is not empty
    if [ -z "$INSERT" ]; then
        echo -e "${cRed}failed${cReset}"
    else
        # Define the MACOS file path
        MACOS_FILE="macos.md"

        # Use
        awk -v insert="$INSERT" '
        /<!-- START OF BREW LINK -->/ {
            print;
            print "```";
            getline;
            print insert;
            while (getline > 0 && !/<!-- END OF BREW LINK -->/) {}
            print "```";
            print
            next
        }
        {print}
    ' "$MACOS_FILE" > "$MACOS_FILE.tmp" && \
            mv "$MACOS_FILE.tmp" "$MACOS_FILE" && \
            echo -e "${cGreen}done${cReset}"
#         sed -i '/<!-- START OF BREW LINK -->/ a \
# ```' "$MACOS_FILE"
    fi
}

function images_to_links(){
awk '{if($0 ~ /img src=/){
    #print $0
    split($0,sp,"\"")
    for(i==0;i<length(sp);i++){
        #print i, sp[i]
        if(sp[i] ~ /^http/){
            link=sp[i]
            break
        }
    }
    link = "<a href=\"" link "\" target=\"_blank\">"
    #print link
    #sub(/^/, "<a href=\"|\" target=\"_blank\">", $0)
    sub(/^/, link, $0)
    sub(/$/, "</a>", $0)
    print $0
} else
print $0}' "$1" | sed 's/<figcaption.*figcaption>//' | sed '/figure>$/d' > "$1".tmp && mv "$1".tmp "$1"
}

while getopts ":ah" opt; do
  case ${opt} in
    a )
      RUN_ALL_PROGRAMS=1
      ;;
    h )
      echo "Usage: $0 [-a/-h]"
      exit
      ;;
  esac
done

mkdir pyradio/__pycache__ 2>/dev/null
rm -rf pyradio/__pycache__/*
echo "This directory is here for pep 517 integration...
Depending on the build system, it may cause problems.
For example:

1. on Arch Linux this will cause the build to fail
   Solution: the directory is deleted before build

2. On other Linux distros (Gentoo, for example) and MacOs
   it will heve to be present

3. There is this README file in the directory; if this
   causes any problems, just remove the README file
   before build
" > pyradio/__pycache__/README
git add pyradio/__pycache__

# update stations_updated in __init.py
ST=$(git status | grep pyradio/stations.csv)
if [ -z "$ST" ];then
    sed -i 's/stations_updated = .*/stations_updated = False/' pyradio/__init__.py
else
    sed -i 's/stations_updated = .*/stations_updated = True/' pyradio/__init__.py
fi


# convert TABs to SPACEs in Changelog
sed -i 's/\t/    /g' Changelog


[ -z "$RUN_ALL_PROGRAMS" ] || ./devel/update_win_players

cd docs
# update brew link in macos.md
[ -z "$RUN_ALL_PROGRAMS" ] ||  update_brew_link

echo -ne "Updating ${cBlue}HTML${cReset} files "

# Create HTML file from md files
for afile in index.md \
    build.md windows.md \
    windows-mplayer.md \
    windows-mpv.md \
    radio-browser.md \
    desktop-notification.md \
    server.md linux.md \
    linux-pipx.md \
    macos.md \
    pip-error.md \
    recording.md \
    packaging.md \
    themes.md \
    headless.md \
    client.md \
    rec-dir.md \
    buffering.md \
    m3u.md \
    validate_playlist.md \
    tts.md \
    os-media-controls.md
do
    sed -i -e "s/'s-/s-/g" -e "s/s'-/s-/g"  "$afile"
    git add "$afile"
    echo -ne '.'
#[ -z "$(git status | grep ${afile})" ] || {
    out=${afile/%.md/.html}
    if [ "$afile" = "index.md" ];then
        echo '% PyRadio Documentation' > tmp.md
    elif [ "$afile" = "build.md" ];then
        echo '% PyRadio Build Instructions' > tmp.md
    elif [ "$afile" = "windows.md" ];then
        echo '% PyRadio on Windows' > tmp.md
    elif [ "$afile" = "windows-mplayer.md" ];then
        echo '% MPlayer Installation on Windows' > tmp.md
    elif [ "$afile" = "windows-mpv.md" ];then
        echo '% MPV Installation on Windows' > tmp.md
    elif [ "$afile" = "radio-browser.md" ];then
        echo '% PyRadio RadioBrowser Implementation' > tmp.md
    elif [ "$afile" = "desktop-notification.md" ];then
        echo '% PyRadio Desktop Notifications' > tmp.md
    elif [ "$afile" = "client.md" ];then
        echo '% PyRadio Remote Control Client' > tmp.md
    elif [ "$afile" = "server.md" ];then
        echo '% PyRadio Remote Control Server' > tmp.md
    elif [ "$afile" = "linux.md" ];then
        echo '% PyRadio pip installation on Linux' > tmp.md
    elif [ "$afile" = "linux-pipx.md" ];then
        echo '% PyRadio pipx installation on Linux' > tmp.md
    elif [ "$afile" = "macos.md" ];then
        echo '% PyRadio pipx installation on MacOS' > tmp.md
    elif [ "$afile" = "pip-error.md" ];then
        echo '% What happened?' > tmp.md
    elif [ "$afile" = "recording.md" ];then
        echo '% Recording stations' > tmp.md
    elif [ "$afile" = "packaging.md" ];then
        echo '% Packaging PyRadio' > tmp.md
    elif [ "$afile" = "themes.md" ];then
        echo '% PyRadio Themes' > tmp.md
    elif [ "$afile" = "headless.md" ];then
        echo '% PyRadio Headless Operation' > tmp.md
    elif [ "$afile" = "rec-dir.md" ];then
        echo '% PyRadio Recordings Directory' > tmp.md
    elif [ "$afile" = "buffering.md" ];then
        echo '% PyRadio Buffering' > tmp.md
    elif [ "$afile" = "m3u.md" ];then
        echo '% PyRadio M3U Playlist Support' > tmp.md
    elif [ "$afile" = "validate_playlist.md" ];then
        echo '% PyRadio Playlist Validation Guide' > tmp.md
    elif [ "$afile" = "tts.md" ];then
        echo '% PyRadio Text-to-Speech Support' > tmp.md
    elif [ "$afile" = "os-media-controls.md" ];then
        echo '% PyRadio Media Controls Support' > tmp.md
    fi
    cat ${afile} >> tmp.md
    pandoc --wrap=none -s -t html tmp.md -o ${out} || {
        echo "Error: pandoc not found"
        rm tmp.md
        exit 1
    }

    sed -i "/<style/,/<.style>/d" ${out}

    # sed -i '/<style[^>]*>/a \

    sed -i '/max-width/d' "${out}"
    sed -i '/<title>/a \
    <style> \
    body {padding: 2em;} \
    @media screen and (max-width: 770px) { \
        body {padding: 10px;} \
    }\
    body {max-width: 750px; margin: auto;} \
    h2 {margin-top: 2.5em; border-bottom:1px solid SaddleBrown; color: SaddleBrown;} \
    h3 {margin-top: 2em; color: SaddleBrown; text-decoration: underline SaddleBrown} \
    h4 {margin: 2em 0 1em 0; color: SaddleBrown; font-size: 1em;} \
    h4:before {content: "# "; font-weight: bold; vertical-align: middle;} \
    h5 {margin: 2em 0 1em 0; color: SaddleBrown; font-size: 1em;;} \
    h5:before {content: "## "; font-weight: bold; vertical-align: middle;} \
    p, table, ol, ul {margin-left: .8em;} \
    STRONG {color: SaddleBrown;} \
    dl {margin: 2em;} \
    dd {margin: 1em;} \
    dt {font-weight: bold;} \
    TABLE {border: 1px solid SaddleBrown; border-collapse: collapse; margin-left: auto; margin-right: auto; border-radius: 5px; -moz-border-radius: 5px; border-collapse:separate; box-shadow: 5px 5px 15px #888888;} \
    TH {text-align: left; vertical-align: top; padding: 5px;color: SaddleBrown;border: 1px solid SaddleBrown; background-color: SaddleBrown; color: white;} \
    TD {text-align: left; vertical-align: top; padding: 5px 10px;border: 1px solid SaddleBrown;} \
    pre { background-color: rgba(245, 245, 245, 1); color: #474747; padding: 1.5em; border: 1px solid #C7C7C7; border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px; overflow: auto; box-shadow: 5px 5px 15px #C7C7C7;} \
    .task-list {list-style-type: none; padding: 0; margin: 0 0 0 1em ;} \
    img{display: block; margin-left: auto; margin-right: auto; max-width: 750px; width: 100%;  background:transparent; padding:3px; border:1px solid #999999; border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px; box-shadow:5px 5px 15px #888888;} \
    .indented {text-indent: -1.5em; padding-left: 1.5em; margin-left: 1em;} \
    </style>' ${out}
    sed -i -e 's/<code>//g' \
        -e 's{</code>{{g' \
        -e 's{<a href="#pyradio">pyradio</a>{[pyradio]{' \
        -e '/^<html/s/lang=""/lang="en"/g' \
        -e 's/<p><strong>Tip:/<p style="margin: 1.5em 4em 0 4em; text-indent: -2em;"><strong>Tip:/' \
        -e 's/<p><strong>Note:/<p style="margin: 1.5em 4em 0 4em; text-indent: -2.5em;"><strong>Note:/' \
        -e 's/\.md">/.html">/g' \
        -e '/h1 class="title"/d' \
        -e 's/<a href="http/<a target="_blank" href="http/g' \
        -e 's{</h2>{ <span style="padding-left: 10px;"><sup style="font-size: 50%"><a href="#" title="Go to top of the page">Top</a></sup></span>&{' \
        -e 's|<.style>$|a{ color: SaddleBrown;}\na:visited{color: SaddleBrown;}\n</style>|' \
        -e 's/<h1 /<h1 style="color: SaddleBrown" /' \
        -e 's/^<p>\[/<p class="indented">[/' \
        ${out}
    rm tmp.md
    if [ "$out" = "windows.html" ] || [ "$out" = "windows-mplayer.html" ];then
        sed -i -e 's/h3 {margin-top: 2em; color: SaddleBrown;}/h3 {margin-top: 2.5em; color: SaddleBrown; border-bottom:1px solid SaddleBrown;}/' \
            -e 's{</h3>{ <span style="padding-left: 10px;"><sup style="font-size: 50%"><a href="#" title="Go to top of the page">Top</a></sup></span>&{' \
            "$out"
    fi
    if [ "$out" = "packaging.html" ];then
        sed -i -e '/img */s/750px/35%/' "$out"
    fi
    #
    # fix #links
    sed -i '/href="#/s/\&#39;//g' "$out"
    #
    # convert images to links
    images_to_links "$out"
    if [ "$out" = "radio-browser.html" ];then
        sed -i -e 's/<sup>N/^N/' \
            -e 's/<.sup>P/^P/' \
            -e 's|N<strong>, </strong>\^P|N</strong>, <strong>^P|' \
            -e 's|<sup>X<strong>|^X</strong>|' \
            -e 's|<.strong>e<strong>|<strong>e</strong>|' \
            -e 's|<.strong><.sup>E<.strong>|<strong>^E</strong>|' \
            "$out"
    fi
    sed -i 's/\.md/.html/' ${out}
    # sed -i 's|^<li>\(.*\)</p>$|<li>\1</li>|' ${out}
    # sed -i 's|^<li><p>\(.*\)</p>$|<li>\1</li>|' ${out}

    if [ "$out" = "index.html" ];then
        sed -i -e '/pyradio.png/s/src=/style="width: 600px" src=/' "$out"
        sed -i -e '/pyradio-limited-display.jpg/s/src=/style="width: 450px" src=/' "$out"
        sed -i -e '/http-force.jpg/s/src=/style="width: 450px" src=/' "$out"
        sed -i -e '/pyradio-buffering-win.jpg/s/src=/style="width: 250px" src=/' "$out"
        sed -i -e '/pyradio-b.jpg/s/src=/style="width: 350px" src=/' "$out"
        sed -i -e '/pyradio-editor.jpg/s/src=/style="width: 600px" src=/' "$out"
        sed -i -e '/pyradio-player-selection.jpg/s/src=/style="width: 600px" src=/' "$out"
        sed -i -e '/pyradio-station-info.jpg/s/src=/style="width: 600px" src=/' "$out"
        sed -i -e '/station-volume.png/s/src=/style="width: 512px" src=/' "$out"
    fi
    if [ "$out" = "desktop-notification.html" ];then
        sed -i -e '/pyradio-notif.jpg/s/src=/style="width: 380px" src=/' "$out"
        sed -i -e '/mac-notif.jpg/s/src=/style="width: 411px" src=/' "$out"
        sed -i -e '/win-notif/s/src=/style="width: 380px" src=/' "$out"
        sed -i -e '/win7-notif/s/src=/style="width: 380px" src=/' "$out"
        sed -i -e '/win-python-props/s/src=/style="width: 574px" src=/' "$out"
        sed -i -e '/win7-icons.jpg/s/src=/style="width: 482px" src=/' "$out"
    fi
    if [ "$out" = "server.html" ];then
        sed -i -e '/server-on.jpg/s/src=/style="width: 350px" src=/' "$out"
        sed -i -e '/phone.jpg/s/src=/style="width: 550px" src=/' "$out"
    fi
    if [ "$out" = "recording.html" ];then
        sed -i -e '/pyradio-recording.\.jpg/s/src=/style="width: 550px" src=/' \
            -e '/mkv-srt-to-chapters\.png/s/src=/style="width: 250px" src=/' \
            "$out"
    fi
    if [ "$out" = "radio-browser.html" ];then
        sed -i -e '/<img /s/src=/style="width: 550px" src=/' \
            "$out"
    fi

    if [ "$out" = "buffering.html" ];then
        sed -i -e '/pyradio-buffering-win.jpg/s/src=/style="width: 280px" src=/' \
            -e '/pyradio-b\.jpg/s/src=/style="width: 450px" src=/' \
            "$out"
    fi

    if [ "$out" = "os-media-controls.html" ];then
        sed -i  -e '/mpris.jpg/s/src=/style="width: 368px" src=/'  -e '/smtc.jpg/s/src=/style="width: 466px" src=/'  -e '/now-playing.jpg/s/src=/style="width: 700px" src=/'  -e 's/support:-/support-/' "$out"
    fi
    
    if [ "$out" = "tts.html" ];then
        sed -i 's/href="#current-status.*roadmap"/href="#current-status-roadmap"/' "$out"
    fi

    sed -i '/^<[Aa]/s|.*|<p>&</p>|' "$out"
    git add ${out}
done

# insert changelog to README.htm
cat << STOP_HERE > pre
<h2 id="changelog">Changelog <span style="padding-left: 10px;"><sup style="font-size: 50%"><a href="#" title="Go to top of the page">Top</a></sup></span></h2>
<pre style="height: 200px;">

STOP_HERE
cat ../Changelog >> pre
echo '</pre>' >> pre

sed -n '1,/<!-- Changelog -->/p' index.html > 1.txt
sed -n '/<!-- Changelog -->/,$p' index.html > 2.txt
cat 1.txt pre 2.txt > index.html
rm 1.txt 2.txt pre

sed -i '/<li><a href="#requirements">Requirements/ a\
<li><a href="#changelog">Changelog</a></li>' index.html
git add index.html
cd ..

cp devel/fix_pyradio_desktop_file pyradio/scripts/
chmod -x pyradio/scripts/fix_pyradio_desktop_file 
git add pyradio/scripts/fix_pyradio_desktop_file

# chmod +x devel/update_win_mplayer
# devel/update_win_mplayer && {
#     git add pyradio/win.py
#     git add devel/update_win_mplayer
# }
echo -e "${cGreen} done${sReset}
"

# sync install.py to common.py
sync_install_py

echo -e "${cBlue}Version:${cReset}"
AVER=$(grep version pyproject.toml | sed -e '2,$d' -e 's/"//'g -e 's/version = //')
echo -en "${cBlue}  pyproject.toml${cReset}:  ${cGreen}"
echo "version = \"$AVER\""

# update version string in __init__.py
XVER=${AVER//./, }
sed -i "s/version_info =.*/version_info = ($XVER)/" pyradio/__init__.py

# update version in install.py
sed -i "s/PyRadioInstallPyReleaseVersion = .*/PyRadioInstallPyReleaseVersion = '$AVER'/" pyradio/install.py
echo -en "${cMagenta}     __init__.py${cReset}:  ${cRed}"
grep '^version_info ' pyradio/__init__.py
echo -en "${cMagenta}      install.py${cReset}:  ${cYellow}"
grep '^PyRadioInstallPyReleaseVersion '  pyradio/install.py

echo -e "${cReset}To change the version, just change the version in ${cGreen}pyproject.toml${cReset}
and all version strings will be updated automatically."

if [ -z "$RUN_ALL_PROGRAMS" ]
then
    echo -e "${cReset}
You should also run
    ${cGreen}${0} -a${cReset}
when you are ready to publish a new release
"
else
    echo
fi

